added authenticated middleware

This commit is contained in:
overflowerror 2021-08-14 17:20:33 +02:00
parent 7a2499999e
commit cdfa816949
4 changed files with 52 additions and 3 deletions

View file

@ -9,8 +9,9 @@ import (
const sessionDuration = 7 * 24 * time.Hour
var (
ErrLoginFailed = errors.New("login failed")
ErrInternalError = errors.New("something went wrong")
ErrLoginFailed = errors.New("login failed")
ErrInvalidSession = errors.New("invalid session")
ErrInternalError = errors.New("something went wrong")
)
func (l *Logic) scheduleTriggerAuth() {
@ -23,7 +24,7 @@ func (l *Logic) scheduleTriggerAuth() {
func (l *Logic) AuthenticateSession(token string) (*models.User, error) {
session, err := l.ctx.Data.GetSession(token)
if err != nil {
return nil, errors.New("invalid session")
return nil, ErrInvalidSession
}
session.ValidUntil = time.Now().Add(sessionDuration)

View file

@ -0,0 +1,11 @@
package presentation
import (
"net/http"
"threadule/backend/internal/web"
)
func GenericStatusResponse(ctx *web.Context, status int) {
ctx.Response.WriteHeader(status)
_, _ = ctx.Response.Write([]byte(http.StatusText(status)))
}

View file

@ -0,0 +1,31 @@
package router
import (
"net/http"
"strings"
"threadule/backend/internal/presentation"
"threadule/backend/internal/web"
)
const authPrefix = "Bearer "
func authenticated(next web.Handler) web.Handler {
return func(ctx *web.Context) {
authHeader := ctx.Request.Header.Get("Authentication")
if !strings.HasPrefix(authHeader, authPrefix) {
presentation.GenericStatusResponse(ctx, http.StatusUnauthorized)
return
}
authHeader = strings.TrimPrefix(authHeader, authPrefix)
user, err := ctx.AppCtx.Logic.AuthenticateSession(authHeader)
if err != nil {
presentation.GenericStatusResponse(ctx, http.StatusUnauthorized)
return
}
ctx.Session.User = user
next(ctx)
}
}

View file

@ -4,11 +4,17 @@ import (
"github.com/julienschmidt/httprouter"
"net/http"
"threadule/backend/internal/app"
"threadule/backend/internal/data/models"
)
type SessionInfo struct {
User *models.User
}
type Context struct {
Response http.ResponseWriter
Request *http.Request
Params httprouter.Params
AppCtx *app.Context
Session SessionInfo
}