happy/web/user_handlers.go

73 lines
1.6 KiB
Go
Raw Permalink Normal View History

package web
import (
"encoding/json"
"fmt"
"net/http"
"github.com/rs/zerolog/log"
)
2019-10-31 14:34:23 +00:00
var Develop = true
type RegisterResponse struct {
ID string
DateCreated int64
Verification string `json:",omitempty"`
}
func (web *Web) handlerRegisterCode(w http.ResponseWriter, r *http.Request) {
uid, err := web.uf.NewUser()
if err != nil {
w.WriteHeader(500)
log.Error().Err(err).Msg("error from NewUserID")
fmt.Fprintf(w, "Error registering user: %s", err)
return
}
if err != nil {
w.WriteHeader(500)
log.Error().Err(err).Msg("error converting date")
fmt.Fprintf(w, "Error registering user: %s", err)
return
}
resp := RegisterResponse{
ID: uid.String(),
DateCreated: uid.DateCreated.Int64,
}
if Develop {
resp.Verification, _ = web.h.EncodeInt64([]int64{uid.Verification})
}
out, err := json.Marshal(resp)
if err != nil {
w.WriteHeader(500)
log.Error().Err(err).Msg("error from json.Marshal")
fmt.Fprintf(w, "Error registering user: %s", err)
return
}
fmt.Fprintf(w, "%s", string(out))
}
func (web *Web) checkUser(w http.ResponseWriter, r *http.Request) {
uid := r.Header.Get("X-user-id")
verify := r.Header.Get("X-user-verification")
log.Debug().
Str("uid", uid).
Str("verify", verify).
Msg("checkUser")
user, err := web.uf.FromStr(uid, verify)
if err != nil {
log.Error().Err(err).Msg("user not known")
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "User not known")
return
}
j, err := json.Marshal(user)
if err != nil {
w.WriteHeader(500)
log.Error().Err(err).Msg("could not marshal user")
fmt.Fprintf(w, "%s", err)
return
}
w.Write(j)
}