This repository has been archived on 2023-11-13. You can view files and clone it, but cannot push or open issues or pull requests.
imagini/routes/auth.go
2021-01-11 23:48:32 -05:00

71 lines
1.8 KiB
Go

package routes
import (
"time"
"encoding/json"
"net/http"
"reichard.io/imagini/internal/auth"
"reichard.io/imagini/internal/models"
// log "github.com/sirupsen/logrus"
)
func (ctx *ImaginiContext) loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
JSONError(w, "Method is not supported.", http.StatusMethodNotAllowed)
return
}
// Decode into Struct
var creds models.APICredentials
err := json.NewDecoder(r.Body).Decode(&creds)
if err != nil {
JSONError(w, "Invalid parameters.", http.StatusBadRequest)
return
}
// Validate
if creds.User == "" || creds.Password == "" {
JSONError(w, "Invalid parameters.", http.StatusBadRequest)
return
}
// TODO: Is user already logged in? If so refresh token, if different user, kill session and log in new user?
// Do login
resp := auth.AuthenticateUser(ctx.DB, creds)
if resp == true {
// Return Success
cookie := http.Cookie{
Name: "Token",
Value: "testToken",
}
http.SetCookie(w, &cookie)
JSONSuccess(w, "Login success.", http.StatusOK)
}else {
// Return Failure
JSONError(w, "Invalid credentials.", http.StatusUnauthorized)
}
}
func (ctx *ImaginiContext) logoutHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method is not supported.", http.StatusMethodNotAllowed)
return
}
// Do logout
// TODO: Clear Session Server Side
// Tell Client to Expire Token
cookie := &http.Cookie{
Name: "Token",
Value: "",
Path: "/",
Expires: time.Unix(0, 0),
HttpOnly: true,
}
http.SetCookie(w, cookie)
}