Merge branch 'sudir_login' into 'master'
implement login with SUDIR auth code See merge request msp2.0/msp-admin-service!7
This commit is contained in:
commit
1db5a1a82e
12 files changed
+381
-38
No files matched your search
@@ -1,3 +1,5 @@
|
||||
### v3.4.0
|
||||
* add method /auth/login_with_sudir
|
||||
### v3.3.1
|
||||
* updated dependencies
|
||||
### v3.3.0
|
||||
|
||||
@@ -10,9 +10,17 @@ type RemoteConfig struct {
|
||||
SecretKey string `valid:"required~Required" schema:"JWT secret"`
|
||||
ExpireSec int `schema:"Token expire time,in seconds"`
|
||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||
}
|
||||
|
||||
type UIDesign struct {
|
||||
Name string `schema:"Название стенда"`
|
||||
PrimaryColor string `schema:"Цвет в HEX, примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
||||
}
|
||||
|
||||
type SudirAuth struct {
|
||||
ClientId string `valid:"required~Required"`
|
||||
ClientSecret string `valid:"required~Required"`
|
||||
Host string `valid:"required~Required" schema:"Хост, пример https://sudir.mos.ru"`
|
||||
RedirectURI string `valid:"required~Required"`
|
||||
}
|
||||
+85
-14
@@ -1,13 +1,16 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/model"
|
||||
"msp-admin-service/service"
|
||||
@@ -17,7 +20,6 @@ import (
|
||||
const adminAuthHeaderName = "x-auth-admin"
|
||||
|
||||
const (
|
||||
ServiceError = "Service is not available now, please try later"
|
||||
ValidationError = "Validation errors"
|
||||
)
|
||||
|
||||
@@ -67,23 +69,25 @@ func GetProfile(metadata metadata.MD) (*structure.AdminUserShort, error) {
|
||||
}
|
||||
|
||||
// @Tags auth
|
||||
// @Summary Авторизация
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body structure.AuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} structure.Auth
|
||||
// @Failure 400 {object} structure.GrpcError "Данные для авторизации не верны"
|
||||
// @Failure 400 {object} structure.GrpcError
|
||||
// @Failure 401 {object} structure.GrpcError "Данные для авторизации не верны"
|
||||
// @Failure 404 {object} structure.GrpcError "Пользователь не найден"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /auth/login [POST]
|
||||
func Login(authRequest structure.AuthRequest) (*structure.Auth, error) {
|
||||
user, err := model.GetUserByEmail(authRequest.Email)
|
||||
if user == nil {
|
||||
return nil, status.Error(codes.NotFound, "User not found")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if user == nil {
|
||||
return nil, status.Error(codes.NotFound, "User not found")
|
||||
} else if user.SudirUserId != "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "User is authorized only with SUDIR")
|
||||
}
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authRequest.Password))
|
||||
if err != nil {
|
||||
@@ -101,6 +105,59 @@ func Login(authRequest structure.AuthRequest) (*structure.Auth, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от СУДИР
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body structure.SudirAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} structure.Auth
|
||||
// @Failure 401 {object} structure.GrpcError "Некорректный код для авторизации"
|
||||
// @Failure 412 {object} structure.GrpcError "Авторизация СУДИР не настроена на сервере"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /auth/login_with_sudir [POST]
|
||||
func LoginWithSudir(request structure.SudirAuthRequest) (*structure.Auth, error) {
|
||||
remoteConfig := config.GetRemote().(*conf.RemoteConfig)
|
||||
if remoteConfig.SudirAuth == nil {
|
||||
return nil, status.Error(codes.FailedPrecondition, "SUDIR authorization is not configured on the server")
|
||||
}
|
||||
|
||||
sudirUser, err := service.AuthSudir(*remoteConfig.SudirAuth, request.AuthCode)
|
||||
var authErr *service.SudirAuthError
|
||||
if errors.As(err, &authErr) {
|
||||
return nil, status.Error(codes.Unauthenticated, err.Error())
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if sudirUser.SudirUserId == "" || sudirUser.Email == "" {
|
||||
return nil, status.Errorf(codes.Unauthenticated, "missing sudirUserId '%s' or email '%s'", sudirUser.SudirUserId, sudirUser.Email)
|
||||
}
|
||||
|
||||
existedUser, err := model.GetUserBySudirUserId(sudirUser.SudirUserId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existedUser != nil {
|
||||
sudirUser = *existedUser
|
||||
} else {
|
||||
sudirUser, err = model.CreateUser(sudirUser)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
tokenString, expired, err := service.GenerateToken(sudirUser.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &structure.Auth{
|
||||
Token: tokenString,
|
||||
Expired: expired,
|
||||
HeaderName: adminAuthHeaderName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
@@ -135,10 +192,13 @@ func GetUsers(identities structure.UsersRequest) (*structure.UsersResponse, erro
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /user/create_update_user [POST]
|
||||
func CreateUpdateUser(user entity.AdminUser) (*entity.AdminUser, error) {
|
||||
var err error
|
||||
if user.Id == 0 {
|
||||
if user.Password == "" {
|
||||
validationErrors := map[string]string{"password": "Requered"}
|
||||
validationErrors := map[string]string{"password": "Required"}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
} else if user.SudirUserId != "" {
|
||||
validationErrors := map[string]string{"sudirUserId": "Could not create user with sudirUserId"}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
}
|
||||
@@ -161,9 +221,11 @@ func CreateUpdateUser(user entity.AdminUser) (*entity.AdminUser, error) {
|
||||
}
|
||||
|
||||
user, err = model.CreateUser(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
var userExists *entity.AdminUser
|
||||
userExists, err = model.GetUserById(user.Id)
|
||||
userExists, err := model.GetUserById(user.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -173,6 +235,14 @@ func CreateUpdateUser(user entity.AdminUser) (*entity.AdminUser, error) {
|
||||
}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.NotFound,
|
||||
ValidationError, validationErrors)
|
||||
} else if userExists.SudirUserId != user.SudirUserId {
|
||||
validationErrors := map[string]string{"sudirUserId": "Could not change sudirUserId of an existing user"}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
} else if user.Password != "" && user.SudirUserId != "" {
|
||||
validationErrors := map[string]string{"password": "Could not set password of a user logged in with SUDIR"}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
}
|
||||
|
||||
if user.Password != "" {
|
||||
@@ -183,16 +253,17 @@ func CreateUpdateUser(user entity.AdminUser) (*entity.AdminUser, error) {
|
||||
}
|
||||
|
||||
user, err = model.UpdateUser(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user.CreatedAt = userExists.CreatedAt
|
||||
user.UpdatedAt = userExists.UpdatedAt
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user.Password = ""
|
||||
|
||||
return &user, err
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// @Tags user
|
||||
|
||||
+79
-9
@@ -1,12 +1,8 @@
|
||||
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
|
||||
// This file was generated by swaggo/swag at
|
||||
// 2021-02-10 16:44:23.355615962 +0300 MSK m=+107.224783060
|
||||
|
||||
// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
|
||||
// This file was generated by swaggo/swag
|
||||
package docs
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/v2/docs"
|
||||
)
|
||||
import "github.com/integration-system/isp-lib/v2/docs"
|
||||
|
||||
var doc = `{
|
||||
"schemes": {{ marshal .Schemes }},
|
||||
@@ -35,7 +31,7 @@ var doc = `{
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Авторизация",
|
||||
"summary": "Авторизация по логину и паролю",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
@@ -55,6 +51,12 @@ var doc = `{
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Данные для авторизации не верны",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
@@ -75,6 +77,58 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/auth/login_with_sudir": {
|
||||
"post": {
|
||||
"description": "Авторизация с получением токена администратора",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Авторизация по авторизационному коду от СУДИР",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.SudirAuthRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.Auth"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Некорректный код для авторизации",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "Авторизация СУДИР не настроена на сервере",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/auth/logout": {
|
||||
"post": {
|
||||
"description": "Выход из авторизованной сессии администрирования",
|
||||
@@ -98,7 +152,9 @@ var doc = `{
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {},
|
||||
"200": {
|
||||
"description": ""
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
@@ -410,6 +466,9 @@ var doc = `{
|
||||
"phone": {
|
||||
"type": "string"
|
||||
},
|
||||
"sudirUserId": {
|
||||
"type": "string"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string"
|
||||
}
|
||||
@@ -503,6 +562,17 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.SudirAuthRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"authCode"
|
||||
],
|
||||
"properties": {
|
||||
"authCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.UsersRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
+50
-2
@@ -25,6 +25,8 @@ definitions:
|
||||
type: string
|
||||
phone:
|
||||
type: string
|
||||
sudirUserId:
|
||||
type: string
|
||||
updatedAt:
|
||||
type: string
|
||||
required:
|
||||
@@ -87,6 +89,13 @@ definitions:
|
||||
type: integer
|
||||
type: array
|
||||
type: object
|
||||
structure.SudirAuthRequest:
|
||||
properties:
|
||||
authCode:
|
||||
type: string
|
||||
required:
|
||||
- authCode
|
||||
type: object
|
||||
structure.UsersRequest:
|
||||
properties:
|
||||
email:
|
||||
@@ -138,6 +147,10 @@ paths:
|
||||
schema:
|
||||
$ref: '#/definitions/structure.Auth'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"401":
|
||||
description: Данные для авторизации не верны
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
@@ -149,7 +162,41 @@ paths:
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
summary: Авторизация
|
||||
summary: Авторизация по логину и паролю
|
||||
tags:
|
||||
- auth
|
||||
/auth/login_with_sudir:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Авторизация с получением токена администратора
|
||||
parameters:
|
||||
- description: Тело запроса
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/structure.SudirAuthRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/structure.Auth'
|
||||
"401":
|
||||
description: Некорректный код для авторизации
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"412":
|
||||
description: Авторизация СУДИР не настроена на сервере
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
summary: Авторизация по авторизационному коду от СУДИР
|
||||
tags:
|
||||
- auth
|
||||
/auth/logout:
|
||||
@@ -166,7 +213,8 @@ paths:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200": {}
|
||||
"200":
|
||||
description: ""
|
||||
"400":
|
||||
description: Невалидный токен
|
||||
schema:
|
||||
|
||||
+11
-10
@@ -12,14 +12,15 @@ type AdminToken struct {
|
||||
}
|
||||
|
||||
type AdminUser struct {
|
||||
tableName string `pg:"?db_schema.users" json:"-"`
|
||||
Id int64 `json:"id"`
|
||||
Image string `json:"image"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Email string `json:"email" valid:"required~Required"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Phone string `json:"phone"`
|
||||
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
|
||||
CreatedAt time.Time `json:"createdAt" sql:",null"`
|
||||
tableName string `pg:"?db_schema.users" json:"-"`
|
||||
SudirUserId string `json:"sudirUserId"`
|
||||
Id int64 `json:"id"`
|
||||
Image string `json:"image"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Email string `json:"email" valid:"required~Required"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Phone string `json:"phone"`
|
||||
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
|
||||
CreatedAt time.Time `json:"createdAt" sql:",null"`
|
||||
}
|
||||
+4
-2
@@ -10,8 +10,9 @@ import (
|
||||
|
||||
type Handlers struct {
|
||||
// ===== AUTH =====
|
||||
Login func(structure.AuthRequest) (*structure.Auth, error) `method:"login" group:"auth" inner:"false"`
|
||||
Logout func(metadata.MD) error `method:"logout" group:"auth" inner:"true"`
|
||||
Login func(structure.AuthRequest) (*structure.Auth, error) `method:"login" group:"auth" inner:"false"`
|
||||
LoginWithSudir func(structure.SudirAuthRequest) (*structure.Auth, error) `method:"login_with_sudir" group:"auth" inner:"false"`
|
||||
Logout func(metadata.MD) error `method:"logout" group:"auth" inner:"true"`
|
||||
|
||||
// ===== USER =====
|
||||
GetProfile func(metadata.MD) (*structure.AdminUserShort, error) `method:"get_profile" group:"user" inner:"true"`
|
||||
@@ -27,6 +28,7 @@ func GetHandlers() []interface{} {
|
||||
return []interface{}{
|
||||
&Handlers{
|
||||
Login: controller.Login,
|
||||
LoginWithSudir: controller.LoginWithSudir,
|
||||
Logout: controller.Logout,
|
||||
GetProfile: controller.GetProfile,
|
||||
GetUIDesign: controller.GetUIDesign,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE users
|
||||
ADD COLUMN sudir_user_id TEXT UNIQUE NULL;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE users
|
||||
DROP COLUMN sudir_user_id;
|
||||
@@ -51,6 +51,17 @@ func GetUserById(identity int64) (*entity.AdminUser, error) {
|
||||
return &user, err
|
||||
}
|
||||
|
||||
func GetUserBySudirUserId(id string) (*entity.AdminUser, error) {
|
||||
var user entity.AdminUser
|
||||
err := DbClient.Unsafe().Model(&user).
|
||||
Where("sudir_user_id = ?", id).
|
||||
First()
|
||||
if err != nil && err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &user, err
|
||||
}
|
||||
|
||||
func GetUsers(usersRequest structure.UsersRequest) (*[]entity.AdminUser, error) {
|
||||
var users []entity.AdminUser
|
||||
query := DbClient.Unsafe().Model(&users)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type sudirTokenResponse struct {
|
||||
*SudirAuthError
|
||||
|
||||
IdToken string `json:"id_token"`
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
Scope string `json:"scope"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
|
||||
type SudirAuthError struct {
|
||||
ErrorName string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
func (s *SudirAuthError) Error() string {
|
||||
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
||||
}
|
||||
|
||||
type sudirUser struct {
|
||||
*SudirAuthError
|
||||
|
||||
UserId string `json:"uid"`
|
||||
Logonname string `json:"logonname"`
|
||||
Firstname string `json:"firstname"`
|
||||
Surname string `json:"surname"`
|
||||
Middlename string `json:"middlename"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func AuthSudir(cfg conf.SudirAuth, authCode string) (entity.AdminUser, error) {
|
||||
tokenResponse, err := getSudirTokens(cfg, authCode)
|
||||
if err != nil {
|
||||
return entity.AdminUser{}, err
|
||||
} else if tokenResponse.SudirAuthError != nil {
|
||||
return entity.AdminUser{}, tokenResponse.SudirAuthError
|
||||
}
|
||||
|
||||
user, err := getSudirUser(cfg.Host, tokenResponse.AccessToken)
|
||||
if err != nil {
|
||||
return entity.AdminUser{}, err
|
||||
} else if user.SudirAuthError != nil {
|
||||
return entity.AdminUser{}, user.SudirAuthError
|
||||
}
|
||||
|
||||
return entity.AdminUser{
|
||||
SudirUserId: user.UserId,
|
||||
FirstName: user.Firstname,
|
||||
LastName: user.Surname,
|
||||
Email: user.Email,
|
||||
Password: "",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getSudirTokens(cfg conf.SudirAuth, authCode string) (sudirTokenResponse, error) {
|
||||
method := cfg.Host + "/blitz/oauth/te"
|
||||
payload := url.Values{
|
||||
"grant_type": []string{"authorization_code"},
|
||||
"code": []string{authCode},
|
||||
"redirect_uri": []string{cfg.RedirectURI},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", method, strings.NewReader(payload.Encode()))
|
||||
if err != nil {
|
||||
return sudirTokenResponse{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.SetBasicAuth(cfg.ClientId, cfg.ClientSecret)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return sudirTokenResponse{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var tokenResponse sudirTokenResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&tokenResponse)
|
||||
if err != nil {
|
||||
return sudirTokenResponse{}, err
|
||||
}
|
||||
|
||||
return tokenResponse, nil
|
||||
}
|
||||
|
||||
func getSudirUser(host, accessToken string) (sudirUser, error) {
|
||||
method := host + "/blitz/oauth/me"
|
||||
|
||||
req, err := http.NewRequest("GET", method, nil)
|
||||
if err != nil {
|
||||
return sudirUser{}, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return sudirUser{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var user sudirUser
|
||||
err = json.NewDecoder(resp.Body).Decode(&user)
|
||||
if err != nil {
|
||||
return sudirUser{}, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -10,3 +10,7 @@ type AuthRequest struct {
|
||||
Email string `json:"email" valid:"required~Required"`
|
||||
Password string `json:"password" valid:"required~Required"`
|
||||
}
|
||||
|
||||
type SudirAuthRequest struct {
|
||||
AuthCode string `json:"authCode" valid:"required~Required"`
|
||||
}
|
||||
Reference in new issue
Block a user