✨ Added login package
For parsing User data from url.Values and validation. close #4
This commit is contained in:
parent
0ed98adbc8
commit
51566f1399
|
@ -0,0 +1,37 @@
|
|||
package login
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// CheckAuthorization verify the authentication and the integrity of the data
|
||||
// received by comparing the received hash parameter with the hexadecimal
|
||||
// representation of the HMAC-SHA-256 signature of the data-check-string with the
|
||||
// SHA256 hash of the bot's token used as a secret key.
|
||||
func (user *User) CheckAuthorization(botToken string) (bool, error) {
|
||||
dataCheckString := fmt.Sprint(
|
||||
"auth_date=", user.AuthDate.Unix(),
|
||||
"\n", "first_name=", user.FirstName,
|
||||
// Eliminate 'hash' to avoid recursion and incorrect data validation.
|
||||
"\n", "id=", user.ID,
|
||||
)
|
||||
|
||||
// Add optional values if exist
|
||||
if user.LastName != "" {
|
||||
dataCheckString += fmt.Sprint("\n", "last_name=", user.LastName)
|
||||
}
|
||||
if user.PhotoURL != "" {
|
||||
dataCheckString += fmt.Sprint("\n", "photo_url=", user.PhotoURL)
|
||||
}
|
||||
if user.Username != "" {
|
||||
dataCheckString += fmt.Sprint("\n", "username=", user.Username)
|
||||
}
|
||||
|
||||
secretKey := sha256.Sum256([]byte(botToken))
|
||||
hash := hmac.New(sha256.New, secretKey[0:])
|
||||
_, err := hash.Write([]byte(dataCheckString))
|
||||
return hex.EncodeToString(hash.Sum(nil)) == user.Hash, err
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
// Package login contains methods for obtaining structure of the user data and
|
||||
// its validation.
|
||||
package login
|
|
@ -0,0 +1,41 @@
|
|||
package login
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User contains data about authenticated user.
|
||||
type User struct {
|
||||
AuthDate time.Time `json:"auth_date"`
|
||||
FirstName string `json:"first_name"`
|
||||
Hash string `json:"hash"`
|
||||
ID int `json:"id"`
|
||||
LastName string `json:"last_name,omitempty"`
|
||||
PhotoURL string `json:"photo_url,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
}
|
||||
|
||||
// New create User structure from input url.Values.
|
||||
func New(src url.Values) (*User, error) {
|
||||
authDate, err := strconv.Atoi(src.Get("auth_date"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
id, err := strconv.Atoi(src.Get("id"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &User{
|
||||
AuthDate: time.Unix(int64(authDate), 0),
|
||||
FirstName: src.Get("first_name"),
|
||||
Hash: src.Get("hash"),
|
||||
ID: id,
|
||||
LastName: src.Get("last_name"),
|
||||
PhotoURL: src.Get("photo_url"),
|
||||
Username: src.Get("username"),
|
||||
}, nil
|
||||
}
|
Loading…
Reference in New Issue