From fb387fe290d907dd8a1b0e3600c5468043071628 Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Sat, 16 Mar 2024 10:35:18 +0530 Subject: api/login: init --- api/login.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ api/main.go | 2 ++ db/account.go | 5 +++-- 3 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 api/login.go diff --git a/api/login.go b/api/login.go new file mode 100644 index 0000000..ef2195e --- /dev/null +++ b/api/login.go @@ -0,0 +1,54 @@ +package api + +import ( + "encoding/json" + "net/http" + + redqdb "sinanmohd.com/redq/db" +) + +type loginAPI struct { + db *redqdb.SafeDB + req *RequestLogin + resp *ResponseLogin +} + +type RequestLogin struct { + Account *redqdb.Account +} + +type ResponseLogin struct { + Account *redqdb.Account +} + +func newLogin(db *redqdb.SafeDB) *loginAPI { + a := &loginAPI{} + a.db = db + + return a +} + +func (a *loginAPI) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + a.req = &RequestLogin{} + a.resp = &ResponseLogin{} + err := unmarshal(r.Body, a.req) + if err != nil { + handleError(err, rw, http.StatusUnprocessableEntity) + return + } + + err = a.req.Account.Login(a.db) + if err != nil { + handleError(err, rw, http.StatusUnauthorized) + return + } + a.resp.Account = a.req.Account + + json, err := json.Marshal(a.resp) + if err != nil { + handleError(err, rw, http.StatusInternalServerError) + return + } + + rw.Write(json) +} diff --git a/api/main.go b/api/main.go index 29f71c9..c4645b8 100644 --- a/api/main.go +++ b/api/main.go @@ -10,6 +10,8 @@ import ( func Run(db *redqdb.SafeDB) { const prefix string = "POST /_redq/api" + login := newLogin(db) + http.Handle(prefix+"/ac/login", login) exampleApi := newExamplApiName(db) http.Handle(prefix+"/example", exampleApi) diff --git a/db/account.go b/db/account.go index b7bcaa0..c7f76bf 100644 --- a/db/account.go +++ b/db/account.go @@ -4,7 +4,7 @@ import "errors" type Account struct { UserName string - PassHash string + PassHash string `json:",omitempty"` Info *Login } @@ -69,9 +69,10 @@ func (ac *Account) Login(safe *SafeDB) error { if err != nil { return err } - if PassHash != ac.PassHash { + if PassHash != ToBlake3(ac.PassHash) { return errors.New("Auth failed") } + ac.PassHash = "" err = ac.Info.Bearer.Generate(safe, ac.Info) if err != nil { -- cgit v1.2.3