home: improve getCurrentUser

This commit is contained in:
Ainar Garipov 2020-12-22 21:09:53 +03:00
parent 925c5df801
commit 1c754788f9
2 changed files with 10 additions and 6 deletions

View File

@ -513,30 +513,34 @@ func (a *Auth) UserFind(login, password string) User {
return User{} return User{}
} }
// GetCurrentUser - get the current user // getCurrentUser returns the current user. It returns an empty User if the
func (a *Auth) GetCurrentUser(r *http.Request) User { // user is not found.
func (a *Auth) getCurrentUser(r *http.Request) User {
cookie, err := r.Cookie(sessionCookieName) cookie, err := r.Cookie(sessionCookieName)
if err != nil { if err != nil {
// there's no Cookie, check Basic authentication // There's no Cookie, check Basic authentication.
user, pass, ok := r.BasicAuth() user, pass, ok := r.BasicAuth()
if ok { if ok {
u := Context.auth.UserFind(user, pass) return Context.auth.UserFind(user, pass)
return u
} }
return User{} return User{}
} }
a.lock.Lock() a.lock.Lock()
defer a.lock.Unlock() defer a.lock.Unlock()
s, ok := a.sessions[cookie.Value] s, ok := a.sessions[cookie.Value]
if !ok { if !ok {
return User{} return User{}
} }
for _, u := range a.users { for _, u := range a.users {
if u.Name == s.userName { if u.Name == s.userName {
return u return u
} }
} }
return User{} return User{}
} }

View File

@ -89,7 +89,7 @@ type profileJSON struct {
func handleGetProfile(w http.ResponseWriter, r *http.Request) { func handleGetProfile(w http.ResponseWriter, r *http.Request) {
pj := profileJSON{} pj := profileJSON{}
u := Context.auth.GetCurrentUser(r) u := Context.auth.getCurrentUser(r)
pj.Name = u.Name pj.Name = u.Name
data, err := json.Marshal(pj) data, err := json.Marshal(pj)