1
0
Fork 0

Added login package

For parsing User data from url.Values and validation. close #4
This commit is contained in:
Maxim Lebedev 2018-02-12 15:46:57 +05:00
parent 0ed98adbc8
commit 51566f1399
No known key found for this signature in database
GPG Key ID: F8978F46FF0FFA4F
3 changed files with 81 additions and 0 deletions

View File

@ -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
}

3
login/doc.go Normal file
View File

@ -0,0 +1,3 @@
// Package login contains methods for obtaining structure of the user data and
// its validation.
package login

41
login/new.go Normal file
View File

@ -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
}