2022-01-04 20:23:25 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2022-05-16 06:15:09 +00:00
|
|
|
"net/http"
|
|
|
|
"nilfm.cc/git/quartzgun/cookie"
|
|
|
|
"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-05-16 06:15:09 +00:00
|
|
|
InitiateSession(user string, password string) (string, error)
|
|
|
|
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
|
|
|
|
SetData(user string, key string, value interface{}) error
|
|
|
|
GetData(user string, key string) (interface{}, 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-05-16 06:15:09 +00:00
|
|
|
session, loginErr := userStore.InitiateSession(user, password)
|
|
|
|
if loginErr == nil {
|
|
|
|
cookie.StoreToken("user", user, w, t)
|
|
|
|
cookie.StoreToken("session", session, w, t)
|
|
|
|
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)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return logoutErr
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|