auth

package
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// OAuthStateKey and OAuthNextKey name the session values that carry a
	// login across the round trip to GitHub. blog sets them when it starts
	// the flow; this package reads them when GitHub returns.
	OAuthStateKey = "oauth_state"
	OAuthNextKey  = "oauth_next"
	// OAuthAdminKey asks GithubCallback to make the GitHub account that
	// comes back an admin, if the browser was signed in as an admin when it
	// returned: how a password admin moves to GitHub login (#668).
	OAuthAdminKey = "oauth_admin"
)
View Source
const (
	ProviderGitHub   = "github"
	ProviderEmail    = "email"
	ProviderPassword = "password"
)

Values for BlogUser.Provider.

View Source
const (
	// MinPasswordLength is in characters. bcrypt reads at most 72 bytes and
	// silently ignores the rest, so longer passwords are refused rather than
	// truncated.
	MinPasswordLength = 10
)

Password login (#654): an admin account that needs nothing outside the server, so a fresh install can be finished without a GitHub OAuth app or an SMTP relay. The install wizard creates the one password user there is; there is no sign-up.

Variables

View Source
var (
	ErrSetupCodeWrong   = errors.New("that is not the setup code")
	ErrSetupRateLimited = errors.New("too many attempts; wait a few minutes and try again")
)

ErrSetupCodeWrong and ErrSetupRateLimited are UnlockSetup's refusals.

View Source
var ErrAdminExists = errors.New("this site already has an admin")

ErrAdminExists is returned by CreatePasswordAdmin once the site has an admin: the wizard creates the first one and nothing more.

View Source
var ErrLastAdmin = errors.New("cannot demote the last admin")

ErrLastAdmin is returned by DemoteAdmin when the demotion would leave the site with no admin at all, which would also re-open the install wizard (IsWizardMode is "no admin_users row").

View Source
var ErrNoPasswordUser = errors.New("no matching password user")

ErrNoPasswordUser is returned by ResetPassword when there is no password user to reset (or none with the given email).

View Source
var ErrNotConfiguredAdmin = errors.New("user is not the configured admin")

ErrNotConfiguredAdmin is returned by EnsureAdmin when no admin exists yet but the logging-in user is not the identity pinned by admin_login / admin_github_id in .env.

Functions

func CheckPassword

func CheckPassword(password string) error

CheckPassword says whether password is acceptable as a new password.

func ClearSetupCode

func ClearSetupCode()

ClearSetupCode forgets the setup code, locking the wizard again. Called once the site has an admin.

func NewOAuthState

func NewOAuthState() (string, error)

NewOAuthState returns an unguessable value to tie an authorize request to the browser that made it.

func NewSetupCode

func NewSetupCode() (string, error)

NewSetupCode makes and remembers a new setup code and returns it formatted for printing (XXXX-XXXX-XXXX).

func SetupUnlocked

func SetupUnlocked(c *gin.Context) bool

SetupUnlocked reports whether this browser has entered the current setup code. The session holds the code itself, not a flag, so a code from before a restart no longer counts.

func UnlockSetup

func UnlockSetup(c *gin.Context, code string) error

UnlockSetup checks code and, when it is right, remembers that in the browser's session.

Types

type AccessTokenResponse

type AccessTokenResponse struct {
	AccessToken string `json:"access_token"`
}

AccessTokenResponse comes from Github OAuth API when the user has successfully authenticated - note the github api provides more fields but we can just leave them out and it will parse just fine - cool!

type AdminUser

type AdminUser struct {
	BlogUserID int
	BlogUser   BlogUser
}

type Auth

type Auth struct {

	// Mailer delivers one-time login codes. nil means email login is not
	// configured and the OTP endpoints respond 404.
	Mailer mail.Sender
	// contains filtered or unexported fields
}

Auth API

func New

func New(db *gorm.DB, version string) Auth

New constructs an Auth API

func (*Auth) AdminExists

func (a *Auth) AdminExists() bool

AdminExists reports whether the site has an admin yet.

func (*Auth) CreatePasswordAdmin

func (a *Auth) CreatePasswordAdmin(email, password string) (*BlogUser, error)

CreatePasswordAdmin creates the site's first admin as a password user and returns it with a fresh session token. It refuses with ErrAdminExists when there already is an admin; the check and both inserts share a transaction so two concurrent requests cannot both succeed.

func (*Auth) CurrentUser

func (a *Auth) CurrentUser(c *gin.Context) *BlogUser

CurrentUser returns the user whose session token is in the request's session, or nil when nobody is logged in (no token, or a token that no longer matches a user).

func (*Auth) DemoteAdmin

func (a *Auth) DemoteAdmin(userID int) error

DemoteAdmin removes the given user's admin status. Returns gorm.ErrRecordNotFound if they are not an admin and ErrLastAdmin if they are the only one.

A transaction alone isn't enough to protect the last admin on Postgres or MySQL: two concurrent demotions could each count two admins and each delete a different one. So the admin rows are read with SELECT ... FOR UPDATE, which serialises concurrent demotions; the second one then sees the row the first removed as gone and refuses. (SQLite has no FOR UPDATE and its driver drops the clause; it serialises writers anyway.)

func (*Auth) DisplayUserTable

func (a *Auth) DisplayUserTable()

DisplayUserTable is a debug function, shows the user table

func (*Auth) EmailLoginEnabled

func (a *Auth) EmailLoginEnabled() bool

EmailLoginEnabled reports whether email login is configured, i.e. whether the login page should offer email login. It mirrors the check the OTP handlers use (Mailer != nil), which main sets once at startup from the environment, so the login page and the endpoints can never disagree.

func (*Auth) EnsureAdmin

func (a *Auth) EnsureAdmin(user *BlogUser) error

EnsureAdmin promotes the given BlogUser to admin if and only if no admin exists yet and the user matches the identity pinned in .env (if any, see isConfiguredAdmin). Returns ErrNotConfiguredAdmin when promotion was refused because of that pin; callers can treat that as "log in as a regular user". Idempotent and safe to call on every login.

The check-and-create runs inside a transaction so two concurrent first logins can't both observe an empty admin_users table and both create a row. Lookup errors other than "record not found" are surfaced rather than swallowed as if no admin existed.

func (*Auth) GithubCallback

func (a *Auth) GithubCallback(c *gin.Context)

GithubCallback handles GitHub's return to /login.

It answers with a redirect either way, so a failure leaves the visitor on the login page rather than on a dead end. ?error=github tells the template something went wrong; a theme that does not render it simply shows the login page again.

func (*Auth) IsAdmin

func (a *Auth) IsAdmin(c *gin.Context) bool

IsAdmin returns true if the user logged in is the admin user. First tries for a session token, and if that fails falls back on an auth token.

Returns false when no admin user exists in the DB. Pre-admin handlers that the install wizard genuinely needs (e.g. UploadFile, UpdateSettings) should also accept IsWizardMode as an exemption.

func (*Auth) IsLoggedIn

func (a *Auth) IsLoggedIn(c *gin.Context) bool

IsLoggedIn Returns true if the user is logged in, false otherwise

func (*Auth) IsWizardMode

func (a *Auth) IsWizardMode(c *gin.Context) bool

IsWizardMode returns true when the install wizard has not yet completed (no row in the admin_users table) and this browser has entered the setup code (see SetupUnlocked). The wizard's own pre-admin endpoints (image upload, initial settings) gate on this so that fresh-install setup can complete before an admin user exists, without being open to whoever else finds the site in the meantime (#658).

func (*Auth) ListUsers

func (a *Auth) ListUsers(offset, limit int) ([]UserListing, int64, error)

ListUsers returns a page of users, newest first, each flagged with whether they are currently admin, along with the total number of users. A query error is returned rather than an empty page that looks like "no users".

func (*Auth) PasswordLogin

func (a *Auth) PasswordLogin(c *gin.Context, next string)

PasswordLogin handles the login page's password form (fields: email, password) and redirects: to next on success, back to the password login page with login_error set otherwise. next must already be a safe same-site path. A wrong password and an unknown email are indistinguishable, in the answer and in how long it takes.

func (*Auth) PasswordLoginEnabled

func (a *Auth) PasswordLoginEnabled() bool

PasswordLoginEnabled reports whether the login page should offer a password form: whether any password user exists.

func (*Auth) PromoteAdmin

func (a *Auth) PromoteAdmin(userID int) error

PromoteAdmin makes the given user an admin. Unlike EnsureAdmin this is not gated on the admin_login / admin_github_id pin: that pin only governs who bootstraps the first admin, after which existing admins decide. Any provider can be promoted: an email login is as strong as its mailbox, which is also what a GitHub account falls back on for recovery (#565). Returns gorm.ErrRecordNotFound for an unknown user. Idempotent.

func (*Auth) RequestUser

func (a *Auth) RequestUser(accessToken string) (*BlogUser, error)

RequestUser fetches the GitHub profile for accessToken and returns it as an unstored BlogUser (ID is zero; the database assigns it on UpsertUser).

func (*Auth) ResetPassword

func (a *Auth) ResetPassword(email string) (string, string, error)

ResetPassword gives a password user a new random password and returns the user's email with it. With email "" it resets the only password user and fails if there is more than one. The user's session token is replaced too, so anyone logged in as them is logged out. For the reset-admin-password command: without SMTP there is no other way back in.

func (*Auth) SendLoginCodeHandler

func (a *Auth) SendLoginCodeHandler(c *gin.Context)

SendLoginCodeHandler handles POST /api/login/email (form field: email). It always answers 200 {"status":"sent"} for a well-formed address whether or not that address has logged in before, so it cannot be used to probe for accounts. Requests inside loginCodeResendAfter of the previous one for the same address get 429, as do clients over loginCodeSendsPerIP sends in loginCodeSendsWindow (checked first, so it isn't itself an oracle for whether a given address was rate-limited).

func (*Auth) StartSession

func (a *Auth) StartSession(c *gin.Context, user *BlogUser) error

StartSession logs user in on this browser, exactly as the other login flows do: the user's AccessToken goes into the session.

func (*Auth) UpdateDb

func (a *Auth) UpdateDb(db *gorm.DB)

func (*Auth) UpsertUser

func (a *Auth) UpsertUser(user *BlogUser) (*BlogUser, error)

UpsertUser stores user, matching an existing row by (Provider, ProviderID). On a miss the row is created and the database assigns ID. On a hit the profile fields and AccessToken are refreshed. Either way the stored row is returned.

func (*Auth) VerifyLoginCodeHandler

func (a *Auth) VerifyLoginCodeHandler(c *gin.Context)

VerifyLoginCodeHandler handles POST /api/login/email/verify (form fields: email, code). A missing, expired, locked or wrong code is a 401 with the same body. Success deletes the code, creates or refreshes the email user with a fresh random session token, and stores that token in the session exactly as the GitHub flow does, so IsLoggedIn works unchanged. Admin promotion is deliberately not attempted here.

type BlogUser

type BlogUser struct {
	ID         int    `gorm:"primaryKey" json:"id"`
	Provider   string `gorm:"uniqueIndex:idx_blog_users_provider;size:32" json:"provider"`
	ProviderID string `gorm:"uniqueIndex:idx_blog_users_provider;size:255" json:"provider_id"`
	Login      string `json:"login"` // github handle, or the email address for email users
	AvatarURL  string `json:"avatar_url"`
	Name       string `json:"name"`
	Email      string `json:"email"`
	// AccessToken is the session credential: the GitHub OAuth token for
	// GitHub users, a random token for email and password users. Never sent
	// to clients.
	AccessToken string `json:"-"`
	// PasswordHash is the bcrypt hash of a password user's password; empty
	// for every other provider. Never sent to clients.
	PasswordHash string `json:"-"`
}

BlogUser is a user of the blog from any login provider. The (Provider, ProviderID) pair identifies the user in the external system: the GitHub numeric id as a string, or the normalised email address (for both email and password users). ID is an internal key assigned by the database. The only role that matters is admin (see AdminUser); otherwise users exist for comments.

func (BlogUser) DisplayName

func (u BlogUser) DisplayName() string

DisplayName is the name to show for the user where one is needed, e.g. as the default author of a comment: the profile name, else the login, with an email-address login reduced to its local part so addresses aren't shown.

type IAuth

type IAuth interface {
	IsAdmin(c *gin.Context) bool
	IsLoggedIn(c *gin.Context) bool
	IsWizardMode(c *gin.Context) bool
	EmailLoginEnabled() bool
	CurrentUser(c *gin.Context) *BlogUser
	ListUsers(offset, limit int) ([]UserListing, int64, error)
	PromoteAdmin(userID int) error
	DemoteAdmin(userID int) error
}

IAuth interface for auth so that it can be mocked easier

type LoginCode

type LoginCode struct {
	Email     string `gorm:"primaryKey;size:254"`
	CodeHash  string `gorm:"size:64"`
	ExpiresAt time.Time
	Attempts  int
	CreatedAt time.Time
}

LoginCode is an outstanding one-time email login code. One row per address; requesting a new code replaces it. The code itself is never stored, only its hex-encoded SHA-256.

type UserListing

type UserListing struct {
	BlogUser
	IsAdmin bool
}

UserListing is a BlogUser with its admin status, for the admin users page.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL