2020-09-08 18:06:39 -04:00
|
|
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
2022-11-27 13:20:29 -05:00
|
|
|
// SPDX-License-Identifier: MIT
|
2020-09-08 18:06:39 -04:00
|
|
|
|
|
|
|
package password
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-02-04 08:29:09 -05:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2020-09-08 18:06:39 -04:00
|
|
|
|
2023-02-19 02:35:20 -05:00
|
|
|
"code.gitea.io/gitea/modules/auth/password/pwn"
|
2020-09-08 18:06:39 -04:00
|
|
|
"code.gitea.io/gitea/modules/setting"
|
|
|
|
)
|
|
|
|
|
2024-02-04 08:29:09 -05:00
|
|
|
var ErrIsPwned = errors.New("password has been pwned")
|
|
|
|
|
|
|
|
type ErrIsPwnedRequest struct {
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
|
|
|
|
func IsErrIsPwnedRequest(err error) bool {
|
|
|
|
_, ok := err.(ErrIsPwnedRequest)
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
|
|
|
func (err ErrIsPwnedRequest) Error() string {
|
|
|
|
return fmt.Sprintf("using Have-I-Been-Pwned service failed: %v", err.err)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (err ErrIsPwnedRequest) Unwrap() error {
|
|
|
|
return err.err
|
|
|
|
}
|
|
|
|
|
2020-09-08 18:06:39 -04:00
|
|
|
// IsPwned checks whether a password has been pwned
|
2024-02-04 08:29:09 -05:00
|
|
|
// If a password has not been pwned, no error is returned.
|
|
|
|
func IsPwned(ctx context.Context, password string) error {
|
2020-09-08 18:06:39 -04:00
|
|
|
if !setting.PasswordCheckPwn {
|
2024-02-04 08:29:09 -05:00
|
|
|
return nil
|
2020-09-08 18:06:39 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
client := pwn.New(pwn.WithContext(ctx))
|
|
|
|
count, err := client.CheckPassword(password, true)
|
|
|
|
if err != nil {
|
2024-02-04 08:29:09 -05:00
|
|
|
return ErrIsPwnedRequest{err}
|
|
|
|
}
|
|
|
|
|
|
|
|
if count > 0 {
|
|
|
|
return ErrIsPwned
|
2020-09-08 18:06:39 -04:00
|
|
|
}
|
|
|
|
|
2024-02-04 08:29:09 -05:00
|
|
|
return nil
|
2020-09-08 18:06:39 -04:00
|
|
|
}
|