authelia/internal/models/totp_configuration.go
James Elliott 1b2af90e5a
feat(commands): totp qr code in png format (#2673)
This allows exporting the TOTP QR code for easy registration when using `authelia storage totp generate` or `authelia storage totp export`.
2022-03-02 18:50:36 +11:00

56 lines
1.4 KiB
Go

package models
import (
"image"
"net/url"
"strconv"
"github.com/pquerna/otp"
)
// TOTPConfiguration represents a users TOTP configuration row in the database.
type TOTPConfiguration struct {
ID int `db:"id" json:"-"`
Username string `db:"username" json:"-"`
Issuer string `db:"issuer" json:"-"`
Algorithm string `db:"algorithm" json:"-"`
Digits uint `db:"digits" json:"digits"`
Period uint `db:"period" json:"period"`
Secret []byte `db:"secret" json:"-"`
}
// URI shows the configuration in the URI representation.
func (c TOTPConfiguration) URI() (uri string) {
v := url.Values{}
v.Set("secret", string(c.Secret))
v.Set("issuer", c.Issuer)
v.Set("period", strconv.FormatUint(uint64(c.Period), 10))
v.Set("algorithm", c.Algorithm)
v.Set("digits", strconv.Itoa(int(c.Digits)))
u := url.URL{
Scheme: "otpauth",
Host: "totp",
Path: "/" + c.Issuer + ":" + c.Username,
RawQuery: v.Encode(),
}
return u.String()
}
// Key returns the *otp.Key using TOTPConfiguration.URI with otp.NewKeyFromURL.
func (c TOTPConfiguration) Key() (key *otp.Key, err error) {
return otp.NewKeyFromURL(c.URI())
}
// Image returns the image.Image of the TOTPConfiguration using the Image func from the return of TOTPConfiguration.Key.
func (c TOTPConfiguration) Image(width, height int) (img image.Image, err error) {
var key *otp.Key
if key, err = c.Key(); err != nil {
return nil, err
}
return key.Image(width, height)
}