cc-backend/internal/auth/local.go

54 lines
1.1 KiB
Go
Raw Normal View History

// Copyright (C) 2022 NHR@FAU, University Erlangen-Nuremberg.
// All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
2022-07-07 14:08:37 +02:00
package auth
2022-07-07 12:11:49 +02:00
import (
"fmt"
"net/http"
"golang.org/x/crypto/bcrypt"
)
type LocalAuthenticator struct {
auth *Authentication
}
var _ Authenticator = (*LocalAuthenticator)(nil)
func (la *LocalAuthenticator) Init(
auth *Authentication,
_ interface{}) error {
2022-07-07 12:11:49 +02:00
la.auth = auth
return nil
}
func (la *LocalAuthenticator) CanLogin(
user *User,
rw http.ResponseWriter,
r *http.Request) bool {
2022-07-07 13:40:38 +02:00
return user != nil && user.AuthSource == AuthViaLocalPassword
2022-07-07 12:11:49 +02:00
}
func (la *LocalAuthenticator) Login(
user *User,
rw http.ResponseWriter,
r *http.Request) (*User, error) {
2022-07-07 13:40:38 +02:00
if e := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(r.FormValue("password"))); e != nil {
return nil, fmt.Errorf("AUTH/LOCAL > user '%s' provided the wrong password (%w)", user.Username, e)
2022-07-07 12:11:49 +02:00
}
2022-07-07 12:48:04 +02:00
return user, nil
2022-07-07 12:11:49 +02:00
}
func (la *LocalAuthenticator) Auth(
rw http.ResponseWriter,
r *http.Request) (*User, error) {
2022-07-07 13:40:38 +02:00
return la.auth.AuthViaSession(rw, r)
2022-07-07 12:11:49 +02:00
}