2022-08-10 05:10:47 +00:00
|
|
|
package session
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
|
2022-08-26 04:21:46 +00:00
|
|
|
"code.nonshy.com/nonshy/website/pkg/models"
|
2022-08-10 05:10:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// CurrentUser returns the current logged in user via session cookie.
|
|
|
|
func CurrentUser(r *http.Request) (*models.User, error) {
|
|
|
|
sess := Get(r)
|
|
|
|
if sess.LoggedIn {
|
2022-08-21 21:17:52 +00:00
|
|
|
// Did we already get the CurrentUser once before?
|
|
|
|
ctx := r.Context()
|
|
|
|
if user, ok := ctx.Value(CurrentUserKey).(*models.User); ok {
|
|
|
|
return user, nil
|
|
|
|
}
|
|
|
|
|
2022-08-10 05:10:47 +00:00
|
|
|
// Load the associated user ID.
|
|
|
|
return models.GetUser(sess.UserID)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errors.New("request session is not logged in")
|
|
|
|
}
|