|
- package endpoints
-
- import (
- "encoding/json"
- "github.com/golang-jwt/jwt/v4"
- "github.com/imosed/signet/auth"
- . "github.com/imosed/signet/data"
- "github.com/spf13/viper"
- "net/http"
- "time"
- )
-
- type LoginResponse struct {
- Token *string `json:"token"`
- }
-
- func Login(w http.ResponseWriter, r *http.Request) {
- var req AuthenticationRequest
- err := json.NewDecoder(r.Body).Decode(&req)
- if err != nil {
- panic("Could not decode body")
- }
-
- var userData struct {
- Id uint
- Password string
- Privileges uint
- }
-
- var resp LoginResponse
- Db.Table("users").Select("id, password, privileges").
- Where("username = ?", req.Username).First(&userData)
- var passwordMatches bool
- passwordMatches, err = ComparePasswordAndHash(req.Password, userData.Password)
- if err != nil {
- panic("Could not compare password to hash")
- }
- if !passwordMatches {
- resp.Token = nil
- err = json.NewEncoder(w).Encode(resp)
- return
- }
-
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, &auth.Claims{
- Username: req.Username,
- Privileges: userData.Privileges,
- RegisteredClaims: jwt.RegisteredClaims{
- ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Hour)),
- },
- })
-
- secret := viper.GetString("app.secretKey")
- tokenString, err := token.SignedString([]byte(secret))
- if err != nil {
- panic("Could not generate JWT token")
- }
- resp.Token = &tokenString
-
- err = json.NewEncoder(w).Encode(resp)
- if err != nil {
- panic("Could not deliver response")
- }
- }
|