2022-01-04 20:23:25 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2024-11-28 17:31:07 +00:00
|
|
|
"forge.lightcrystal.systems/nilix/quartzgun/cookie"
|
2023-07-13 23:31:20 +00:00
|
|
|
"net/http"
|
2022-05-16 06:15:09 +00:00
|
|
|
"time"
|
2022-01-04 20:23:25 +00:00
|
|
|
)
|
|
|
|
|
2022-01-08 05:52:37 +00:00
|
|
|
type User struct {
|
2022-05-16 06:15:09 +00:00
|
|
|
Name string
|
|
|
|
Pass string
|
|
|
|
Session string
|
|
|
|
LoginTime time.Time
|
|
|
|
LastSeen time.Time
|
2022-01-08 05:52:37 +00:00
|
|
|
|
2022-05-16 06:15:09 +00:00
|
|
|
Data map[string]interface{}
|
2022-01-08 05:52:37 +00:00
|
|
|
}
|
|
|
|
|
2022-01-04 20:23:25 +00:00
|
|
|
type UserStore interface {
|
2022-08-03 02:46:34 +00:00
|
|
|
InitiateSession(user string, password string, ttl int) (string, error)
|
2022-05-16 06:15:09 +00:00
|
|
|
ValidateUser(user string, sessionId string) (bool, error)
|
|
|
|
EndSession(user string) error
|
|
|
|
AddUser(user string, password string) error
|
|
|
|
DeleteUser(user string) error
|
|
|
|
ChangePassword(user string, oldPassword string, newPassword string) error
|
2022-05-21 03:36:54 +00:00
|
|
|
GetLastLoginTime(user string) (time.Time, error)
|
|
|
|
GetLastTimeSeen(user string) (time.Time, error)
|
2022-05-16 06:15:09 +00:00
|
|
|
SetData(user string, key string, value interface{}) error
|
|
|
|
GetData(user string, key string) (interface{}, error)
|
2022-08-03 02:46:34 +00:00
|
|
|
GrantToken(user, password string, ttl int) (string, error)
|
2022-08-01 00:08:05 +00:00
|
|
|
ValidateToken(token string) (bool, error)
|
|
|
|
ValidateTokenWithScopes(token string, scopes map[string]string) (bool, error)
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|
|
|
|
|
2022-01-11 06:30:20 +00:00
|
|
|
func Login(user string, password string, userStore UserStore, w http.ResponseWriter, t int) error {
|
2022-08-03 02:46:34 +00:00
|
|
|
session, loginErr := userStore.InitiateSession(user, password, t)
|
2022-05-16 06:15:09 +00:00
|
|
|
if loginErr == nil {
|
|
|
|
cookie.StoreToken("user", user, w, t)
|
|
|
|
cookie.StoreToken("session", session, w, t)
|
2022-05-21 03:36:54 +00:00
|
|
|
csrfToken := cookie.GenToken(64)
|
|
|
|
cookie.StoreToken("csrfToken", csrfToken, w, t)
|
|
|
|
userStore.SetData(user, "csrfToken", csrfToken)
|
2022-05-16 06:15:09 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return loginErr
|
2022-01-11 06:30:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func Logout(user string, userStore UserStore, w http.ResponseWriter) error {
|
2022-05-16 06:15:09 +00:00
|
|
|
logoutErr := userStore.EndSession(user)
|
|
|
|
if logoutErr == nil {
|
|
|
|
cookie.StoreToken("user", "", w, 0)
|
|
|
|
cookie.StoreToken("session", "", w, 0)
|
2022-05-21 03:36:54 +00:00
|
|
|
cookie.StoreToken("csrfToken", "", w, 0)
|
|
|
|
userStore.SetData(user, "csrfToken", "")
|
2022-05-16 06:15:09 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return logoutErr
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|