1package login
2
3import (
4	"context"
5	"crypto/subtle"
6
7	"github.com/grafana/grafana/pkg/bus"
8	"github.com/grafana/grafana/pkg/models"
9	"github.com/grafana/grafana/pkg/util"
10)
11
12var validatePassword = func(providedPassword string, userPassword string, userSalt string) error {
13	passwordHashed, err := util.EncodePassword(providedPassword, userSalt)
14	if err != nil {
15		return err
16	}
17	if subtle.ConstantTimeCompare([]byte(passwordHashed), []byte(userPassword)) != 1 {
18		return ErrInvalidCredentials
19	}
20
21	return nil
22}
23
24var loginUsingGrafanaDB = func(ctx context.Context, query *models.LoginUserQuery) error {
25	userQuery := models.GetUserByLoginQuery{LoginOrEmail: query.Username}
26
27	if err := bus.DispatchCtx(ctx, &userQuery); err != nil {
28		return err
29	}
30
31	user := userQuery.Result
32
33	if user.IsDisabled {
34		return ErrUserDisabled
35	}
36
37	if err := validatePassword(query.Password, user.Password, user.Salt); err != nil {
38		return err
39	}
40
41	query.User = user
42	return nil
43}
44