Files

88 lines
2.4 KiB
Go
Raw Permalink Normal View History

2021-07-24 11:16:34 +01:00
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2021-07-24 11:16:34 +01:00
package smtp
import (
2023-09-14 19:09:32 +02:00
"context"
2021-07-24 11:16:34 +01:00
"errors"
"net/smtp"
"net/textproto"
"strings"
2022-01-02 21:12:35 +08:00
auth_model "code.gitea.io/gitea/models/auth"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/optional"
2021-07-24 11:16:34 +01:00
"code.gitea.io/gitea/modules/util"
)
// Authenticate queries if the provided login/password is authenticates against the SMTP server
// Users will be autoregistered as required
2023-09-14 19:09:32 +02:00
func (source *Source) Authenticate(ctx context.Context, user *user_model.User, userName, password string) (*user_model.User, error) {
2021-07-24 11:16:34 +01:00
// Verify allowed domains.
if len(source.AllowedDomains) > 0 {
2025-12-04 10:06:44 +01:00
_, after, ok := strings.Cut(userName, "@")
if !ok {
return nil, user_model.ErrUserNotExist{Name: userName}
2025-12-04 10:06:44 +01:00
} else if !util.SliceContainsString(strings.Split(source.AllowedDomains, ","), after, true) {
return nil, user_model.ErrUserNotExist{Name: userName}
2021-07-24 11:16:34 +01:00
}
}
var auth smtp.Auth
switch source.Auth {
case PlainAuthentication:
auth = smtp.PlainAuth("", userName, password, source.Host)
case LoginAuthentication:
auth = &loginAuthenticator{userName, password}
case CRAMMD5Authentication:
auth = smtp.CRAMMD5Auth(userName, password)
default:
return nil, errors.New("unsupported SMTP auth type")
2021-07-24 11:16:34 +01:00
}
if err := Authenticate(auth, source); err != nil {
// Check standard error format first,
// then fallback to worse case.
tperr, ok := err.(*textproto.Error)
if (ok && tperr.Code == 535) ||
strings.Contains(err.Error(), "Username and Password not accepted") {
return nil, user_model.ErrUserNotExist{Name: userName}
2021-07-24 11:16:34 +01:00
}
if (ok && tperr.Code == 534) ||
strings.Contains(err.Error(), "Application-specific password required") {
return nil, user_model.ErrUserNotExist{Name: userName}
}
2021-07-24 11:16:34 +01:00
return nil, err
}
if user != nil {
return user, nil
}
username := userName
2025-12-04 10:06:44 +01:00
before, _, ok := strings.Cut(userName, "@")
if ok {
username = before
2021-07-24 11:16:34 +01:00
}
user = &user_model.User{
2021-07-24 11:16:34 +01:00
LowerName: strings.ToLower(username),
Name: strings.ToLower(username),
Email: userName,
2021-07-24 11:16:34 +01:00
Passwd: password,
2022-01-02 21:12:35 +08:00
LoginType: auth_model.SMTP,
LoginSource: source.AuthSource.ID,
LoginName: userName,
}
overwriteDefault := &user_model.CreateUserOverwriteOptions{
IsActive: optional.Some(true),
2021-07-24 11:16:34 +01:00
}
if err := user_model.CreateUser(ctx, user, &user_model.Meta{}, overwriteDefault); err != nil {
return user, err
}
return user, nil
2021-07-24 11:16:34 +01:00
}