-
-
Notifications
You must be signed in to change notification settings - Fork 106
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
20 changed files
with
629 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package totp | ||
|
||
import ( | ||
"bytes" | ||
"crypto/rand" | ||
"encoding/base64" | ||
"github.com/pquerna/otp/totp" | ||
"html/template" | ||
"image/png" | ||
"strings" | ||
) | ||
|
||
const secretSize = 16 | ||
|
||
func GenerateQRCode(username, siteUrl string, secret []byte) (string, template.URL, error, []byte) { | ||
var err error | ||
if secret == nil { | ||
secret, err = generateSecret() | ||
if err != nil { | ||
return "", "", err, nil | ||
} | ||
} | ||
|
||
otpKey, err := totp.Generate(totp.GenerateOpts{ | ||
SecretSize: secretSize, | ||
Issuer: "Opengist (" + strings.ReplaceAll(siteUrl, ":", "") + ")", | ||
AccountName: username, | ||
Secret: secret, | ||
}) | ||
if err != nil { | ||
return "", "", err, nil | ||
} | ||
|
||
qrcode, err := otpKey.Image(320, 240) | ||
if err != nil { | ||
return "", "", err, nil | ||
} | ||
|
||
var imgBytes bytes.Buffer | ||
if err = png.Encode(&imgBytes, qrcode); err != nil { | ||
return "", "", err, nil | ||
} | ||
|
||
qrcodeImage := template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(imgBytes.Bytes())) | ||
|
||
return otpKey.Secret(), qrcodeImage, nil, secret | ||
} | ||
|
||
func Validate(passcode, secret string) bool { | ||
return totp.Validate(passcode, secret) | ||
} | ||
|
||
func generateSecret() ([]byte, error) { | ||
secret := make([]byte, secretSize) | ||
_, err := rand.Reader.Read(secret) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return secret, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
package db | ||
|
||
import ( | ||
"crypto/rand" | ||
"encoding/base64" | ||
"encoding/hex" | ||
"encoding/json" | ||
"fmt" | ||
ogtotp "github.com/thomiceli/opengist/internal/auth/totp" | ||
"github.com/thomiceli/opengist/internal/utils" | ||
"slices" | ||
) | ||
|
||
type TOTP struct { | ||
ID uint `gorm:"primaryKey"` | ||
UserID uint `gorm:"uniqueIndex"` | ||
User User | ||
Secret string | ||
RecoveryCodes jsonData `gorm:"type:json"` | ||
CreatedAt int64 | ||
LastUsedAt int64 | ||
} | ||
|
||
func GetTOTPByUserID(userID uint) (*TOTP, error) { | ||
var totp TOTP | ||
err := db.Where("user_id = ?", userID).First(&totp).Error | ||
return &totp, err | ||
} | ||
|
||
func (totp *TOTP) StoreSecret(secret string) error { | ||
secretBytes := []byte(secret) | ||
encrypted, err := utils.AESEncrypt([]byte("tmp"), secretBytes) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
totp.Secret = base64.URLEncoding.EncodeToString(encrypted) | ||
return nil | ||
} | ||
|
||
func (totp *TOTP) ValidateCode(code string) (bool, error) { | ||
ciphertext, err := base64.URLEncoding.DecodeString(totp.Secret) | ||
if err != nil { | ||
return false, err | ||
} | ||
|
||
secretBytes, err := utils.AESDecrypt([]byte("tmp"), ciphertext) | ||
if err != nil { | ||
return false, err | ||
} | ||
|
||
return ogtotp.Validate(code, string(secretBytes)), nil | ||
} | ||
|
||
func (totp *TOTP) ValidateRecoveryCode(code string) (bool, error) { | ||
var hashedCodes []string | ||
if err := json.Unmarshal(totp.RecoveryCodes, &hashedCodes); err != nil { | ||
return false, err | ||
} | ||
|
||
for i, hashedCode := range hashedCodes { | ||
ok, err := utils.Argon2id.Verify(code, hashedCode) | ||
if err != nil { | ||
return false, err | ||
} | ||
if ok { | ||
codesJson, _ := json.Marshal(slices.Delete(hashedCodes, i, i+1)) | ||
totp.RecoveryCodes = codesJson | ||
return true, db.Model(&totp).Updates(TOTP{RecoveryCodes: codesJson}).Error | ||
} | ||
} | ||
return false, nil | ||
} | ||
|
||
func (totp *TOTP) GenerateRecoveryCodes() ([]string, error) { | ||
codes, plainCodes, err := generateRandomCodes() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
codesJson, _ := json.Marshal(codes) | ||
totp.RecoveryCodes = codesJson | ||
|
||
return plainCodes, db.Model(&totp).Updates(TOTP{RecoveryCodes: codesJson}).Error | ||
} | ||
|
||
func (totp *TOTP) Create() error { | ||
return db.Create(&totp).Error | ||
} | ||
|
||
func (totp *TOTP) Delete() error { | ||
return db.Delete(&totp).Error | ||
} | ||
|
||
func generateRandomCodes() ([]string, []string, error) { | ||
const count = 5 | ||
const length = 10 | ||
codes := make([]string, count) | ||
plainCodes := make([]string, count) | ||
for i := 0; i < count; i++ { | ||
bytes := make([]byte, (length+1)/2) | ||
if _, err := rand.Read(bytes); err != nil { | ||
return nil, nil, err | ||
} | ||
hexCode := hex.EncodeToString(bytes) | ||
code := fmt.Sprintf("%s-%s", hexCode[:length/2], hexCode[length/2:]) | ||
plainCodes[i] = code | ||
hashed, err := utils.Argon2id.Hash(code) | ||
if err != nil { | ||
return nil, nil, err | ||
} | ||
codes[i] = hashed | ||
} | ||
return codes, plainCodes, nil | ||
} | ||
|
||
// -- DTO -- // | ||
|
||
type TOTPDTO struct { | ||
Code string `form:"code" validate:"max=50"` | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package utils | ||
|
||
import ( | ||
"crypto/aes" | ||
"crypto/cipher" | ||
"crypto/rand" | ||
"fmt" | ||
"io" | ||
) | ||
|
||
func AESEncrypt(key, text []byte) ([]byte, error) { | ||
block, err := aes.NewCipher(key) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
ciphertext := make([]byte, aes.BlockSize+len(text)) | ||
iv := ciphertext[:aes.BlockSize] | ||
if _, err = io.ReadFull(rand.Reader, iv); err != nil { | ||
return nil, err | ||
} | ||
|
||
stream := cipher.NewCFBEncrypter(block, iv) | ||
stream.XORKeyStream(ciphertext[aes.BlockSize:], text) | ||
|
||
return ciphertext, nil | ||
} | ||
|
||
func AESDecrypt(key, ciphertext []byte) ([]byte, error) { | ||
block, err := aes.NewCipher(key) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
if len(ciphertext) < aes.BlockSize { | ||
return nil, fmt.Errorf("ciphertext too short") | ||
} | ||
|
||
iv := ciphertext[:aes.BlockSize] | ||
ciphertext = ciphertext[aes.BlockSize:] | ||
|
||
stream := cipher.NewCFBDecrypter(block, iv) | ||
stream.XORKeyStream(ciphertext, ciphertext) | ||
|
||
return ciphertext, nil | ||
} |
Oops, something went wrong.