2021-01-10 00:44:02 +00:00
|
|
|
package routes
|
|
|
|
|
|
|
|
import (
|
2021-01-12 04:48:32 +00:00
|
|
|
"time"
|
|
|
|
"encoding/json"
|
2021-01-10 00:44:02 +00:00
|
|
|
"net/http"
|
2021-01-12 04:48:32 +00:00
|
|
|
|
|
|
|
"reichard.io/imagini/internal/auth"
|
|
|
|
"reichard.io/imagini/internal/models"
|
|
|
|
// log "github.com/sirupsen/logrus"
|
2021-01-10 00:44:02 +00:00
|
|
|
)
|
|
|
|
|
2021-01-12 04:48:32 +00:00
|
|
|
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
|
|
|
|
}
|
2021-01-10 00:44:02 +00:00
|
|
|
|
2021-01-12 04:48:32 +00:00
|
|
|
// 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)
|
|
|
|
}
|
2021-01-10 00:44:02 +00:00
|
|
|
}
|
|
|
|
|
2021-01-12 04:48:32 +00:00
|
|
|
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
|
2021-01-10 00:44:02 +00:00
|
|
|
|
2021-01-12 04:48:32 +00:00
|
|
|
// Tell Client to Expire Token
|
|
|
|
cookie := &http.Cookie{
|
|
|
|
Name: "Token",
|
|
|
|
Value: "",
|
|
|
|
Path: "/",
|
|
|
|
Expires: time.Unix(0, 0),
|
|
|
|
HttpOnly: true,
|
|
|
|
}
|
|
|
|
http.SetCookie(w, cookie)
|
2021-01-10 00:44:02 +00:00
|
|
|
}
|