2018-02-12 10:46:57 +00:00
|
|
|
package login
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/hex"
|
2018-04-12 13:13:56 +00:00
|
|
|
"errors"
|
|
|
|
"net/url"
|
|
|
|
"strconv"
|
2018-02-12 10:46:57 +00:00
|
|
|
)
|
|
|
|
|
2018-04-19 13:02:15 +00:00
|
|
|
// ErrUserNotDefined describes error of an unassigned structure of user
|
2018-04-12 13:13:56 +00:00
|
|
|
var ErrUserNotDefined = errors.New("user is not defined")
|
|
|
|
|
2018-02-12 10:46:57 +00:00
|
|
|
// 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.
|
2018-08-21 11:05:04 +00:00
|
|
|
func (a *App) CheckAuthorization(user *User) (ok bool, err error) {
|
2018-04-12 13:13:56 +00:00
|
|
|
if user == nil {
|
2018-08-21 11:05:04 +00:00
|
|
|
err = ErrUserNotDefined
|
|
|
|
return
|
2018-04-12 13:13:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
dataCheck := make(url.Values)
|
|
|
|
dataCheck.Add(KeyAuthDate, string(user.AuthDate))
|
|
|
|
dataCheck.Add(KeyFirstName, user.FirstName)
|
|
|
|
dataCheck.Add(KeyID, strconv.Itoa(user.ID))
|
2018-02-12 10:46:57 +00:00
|
|
|
|
|
|
|
// Add optional values if exist
|
|
|
|
if user.LastName != "" {
|
2018-04-12 13:13:56 +00:00
|
|
|
dataCheck.Add(KeyLastName, user.LastName)
|
2018-02-12 10:46:57 +00:00
|
|
|
}
|
|
|
|
if user.PhotoURL != "" {
|
2018-04-12 13:13:56 +00:00
|
|
|
dataCheck.Add(KeyPhotoURL, user.PhotoURL)
|
2018-02-12 10:46:57 +00:00
|
|
|
}
|
|
|
|
if user.Username != "" {
|
2018-04-12 13:13:56 +00:00
|
|
|
dataCheck.Add(KeyUsername, user.Username)
|
2018-02-12 10:46:57 +00:00
|
|
|
}
|
|
|
|
|
2018-08-21 11:05:04 +00:00
|
|
|
secretKey := sha256.Sum256([]byte(a.SecretKey))
|
2018-02-12 10:46:57 +00:00
|
|
|
hash := hmac.New(sha256.New, secretKey[0:])
|
2018-08-21 11:05:04 +00:00
|
|
|
if _, err = hash.Write([]byte(dataCheck.Encode())); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ok = hex.EncodeToString(hash.Sum(nil)) == user.Hash
|
|
|
|
return
|
2018-02-12 10:46:57 +00:00
|
|
|
}
|