internal/auth.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
package internal import ( "encoding/json" "net/http" "time" "watchman/schema" "watchman/utils" "github.com/golang-jwt/jwt/v5" ) func AdminLogin(w http.ResponseWriter, r *http.Request) { utils.HandleMethodNotAllowed(w, r, http.MethodPost) config := utils.Read_Config() var user schema.User decoder := json.NewDecoder(r.Body) err := decoder.Decode(&user) if err != nil { utils.HandleError(w, r, http.StatusBadRequest, "Error decoding JSON: ", nil) } if user.Username != config.Admin.Username || user.Password != config.Admin.Password { response := schema.Response_Type{ Status: "ERROR", Message: "Invalid credentials", RequestID: r.Context().Value(schema.RequestIDKey{}).(string), } w.WriteHeader(http.StatusUnauthorized) utils.SendResponse(w, r, response) return } expirationTime := time.Now().Add(30 * time.Minute) claims := &schema.Claims{ Username: user.Username, RegisteredClaims: jwt.RegisteredClaims{ ExpiresAt: jwt.NewNumericDate(expirationTime), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenString, err := token.SignedString(config.JwtKey) if err != nil { utils.HandleError(w, r, http.StatusInternalServerError, "Error signing token: ", err) return } http.SetCookie(w, &http.Cookie{ Name: "token", Value: tokenString, Expires: expirationTime, }) response := schema.Response_Type{ Status: "OK", Message: "Login successful", RequestID: r.Context().Value(schema.RequestIDKey{}).(string), Data: map[string]string{ "token": tokenString, "expires_at": expirationTime.String(), }, } utils.SendResponse(w, r, response) } |