How to use AuthenticateUser method of oauth Package

Best Testkube code snippet using oauth.AuthenticateUser

main.go

Source:main.go Github

copy

Full Screen

...21)22type Connector interface {23 GetClient(key, secret string) (interface{}, error)24 GetUserFromAccessToken(accessToken string) (interface{}, error)25 AuthenticateUser(username, password string) (interface{}, error)26 GetAccessToken(interface{}, interface{}) (JSONAble, error)27}28type JSONAble interface {29 ToJSON() ([]byte, error)30}31var kConnector Connector32type OAuthError struct {33 HTTPStatusCode int34 Err string35 Description string36}37func (e *OAuthError) Error() (err string) {38 err = "OAuth Error: " + e.Err39 if len(e.Description) > 0 {40 err += " " + e.Description41 }42 return43}44func (e *OAuthError) ToJSON() (rt []byte, err error) {45 obj := make(map[string]string)46 if len(e.Err) > 0 {47 obj["error"] = e.Err48 } else {49 obj["error"] = "unknown"50 }51 if len(e.Description) > 0 {52 obj["error_description"] = e.Description53 }54 rt, err = json.Marshal(obj)55 return56}57func getAccessToken(req *http.Request) (accessToken string, err *OAuthError) {58 /*59 * Check Query String60 */61 query := req.URL.Query()62 accessTokenQuery, exists := query["access_token"]63 if exists && len(accessTokenQuery[0]) > 0 {64 accessToken = accessTokenQuery[0]65 return66 }67 /*68 * Check Authorization Header69 */70 accessToken, err = getAuthorizationHeaderValue(req, "Bearer")71 return72}73func SetConnector(connector Connector) {74 kConnector = connector75}76func GetUserOrFail(res http.ResponseWriter, req *http.Request) interface{} {77 accessToken, err := getAccessToken(req)78 if err != nil {79 oauthErrorReply(res, *err)80 return nil81 }82 user, fail := kConnector.GetUserFromAccessToken(accessToken)83 if fail != nil {84 log.Error("[OAuth] Cannot retreive user form access token: " + fail.Error())85 oauthErrorReply(res, OAuthError{500, SERVER_ERROR, "Internal Server Error"})86 return nil87 }88 if user != nil {89 return user90 }91 oauthErrorReply(res, OAuthError{403, ACCESS_DENIED, "Invalid access token"})92 return nil93}94func getAuthorizationHeaderValue(req *http.Request, authType string) (string, *OAuthError) {95 rawHeader := req.Header.Get("Authorization")96 if len(rawHeader) < 1 {97 return "", &OAuthError{403, INVALID_REQUEST, "Authorization header is missing"}98 }99 splt := strings.SplitN(rawHeader, " ", 2)100 if len(splt) != 2 {101 return "", &OAuthError{403, INVALID_REQUEST, "Invalid Authorization header"}102 }103 if splt[0] != authType {104 return "", &OAuthError{403, INVALID_REQUEST, "Invalid authorization type"}105 }106 token := splt[1]107 return token, nil108}109func clientBasicAuth(req *http.Request) (interface{}, *OAuthError) {110 rawAuthToken, err := getAuthorizationHeaderValue(req, "Basic")111 if err != nil {112 return nil, err113 }114 log.Debug("[OAuth] token = " + rawAuthToken)115 bToken, fail := base64.StdEncoding.DecodeString(rawAuthToken)116 if fail != nil {117 log.Warn("[Oauth] Unable to parse base64 auth basic string: " + rawAuthToken)118 return nil, &OAuthError{403, INVALID_REQUEST, "Invalid Authorization header"}119 }120 token := string(bToken)121 splt := strings.SplitN(token, ":", 2)122 if len(splt) != 2 {123 return nil, &OAuthError{403, INVALID_REQUEST, "Invalid Authorization header"}124 }125 clientKey := splt[0]126 clientSecret := splt[1]127 client, fail := kConnector.GetClient(clientKey, clientSecret)128 if fail != nil {129 log.Error("[Oauth] Unable to retreive client: " + fail.Error())130 return nil, &OAuthError{500, SERVER_ERROR, "Internal Server Error"}131 }132 return client, nil133}134func oauthErrorReply(res http.ResponseWriter, oauthErr OAuthError) error {135 res.Header().Set("Content-Type", "application/json;charset=UTF-8")136 ret, err := oauthErr.ToJSON()137 if err != nil {138 log.Error("[OAuth] Cannot write JSON error: " + err.Error())139 return err140 }141 res.WriteHeader(oauthErr.HTTPStatusCode)142 res.Write(ret)143 return nil144}145func isJSON(contentType string) bool {146 return strings.SplitN(contentType, ";", 2)[0] == "application/json"147}148func HandleRequest(res http.ResponseWriter, req *http.Request) {149 res.Header().Add("Cache-Control", "no-store")150 res.Header().Add("Pragma", "no-cache")151 if req.Method == "POST" && req.URL.Path == "/oauth/token" {152 client, err := clientBasicAuth(req)153 if err != nil {154 oauthErrorReply(res, *err)155 return156 }157 if client == nil {158 oauthErrorReply(res, OAuthError{401, INVALID_CLIENT, "Invalid OAuth Client Credentials"})159 return160 }161 if !isJSON(req.Header.Get("Content-Type")) {162 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "Only JSON body is accepted"})163 return164 }165 decoder := json.NewDecoder(req.Body)166 form := make(map[string]interface{})167 fail := decoder.Decode(&form)168 if fail != nil {169 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "Unable to parse the request body"})170 return171 }172 // grant_type173 raw := form["grant_type"]174 if raw == nil {175 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "grant_type is missing"})176 return177 }178 grantType, isString := raw.(string)179 if !isString {180 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "grant_type is invalid"})181 return182 }183 if grantType != "password" {184 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "Invalid grant_type"})185 return186 }187 // username188 raw = form["username"]189 if raw == nil {190 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "username is missing"})191 return192 }193 username, isString := raw.(string)194 if !isString {195 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "username is invalid"})196 return197 }198 // password199 raw = form["password"]200 if raw == nil {201 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "password is missing"})202 return203 }204 password, isString := raw.(string)205 if !isString {206 oauthErrorReply(res, OAuthError{400, INVALID_REQUEST, "password is invalid"})207 return208 }209 user, fail := kConnector.AuthenticateUser(username, password)210 if fail != nil {211 log.Error("[OAuth] Cannot Authenticate User: " + fail.Error())212 oauthErrorReply(res, OAuthError{400, SERVER_ERROR, "Internal Server Error"})213 return214 }215 if user == nil {216 oauthErrorReply(res, OAuthError{401, ACCESS_DENIED, "Invalid User Credentials"})217 return218 }219 accessToken, fail := kConnector.GetAccessToken(user, client)220 if fail != nil {221 log.Error("[OAuth] Cannot Get Access Token: " + fail.Error())222 oauthErrorReply(res, OAuthError{500, SERVER_ERROR, "Internal Server Error"})223 return224 }225 if accessToken == nil {226 oauthErrorReply(res, OAuthError{401, ACCESS_DENIED, "Access token request denied for the given client"})227 return228 }229 rt, fail := accessToken.ToJSON()230 if fail != nil {231 log.Error("[OAuth] Unable to serialize access token: " + fail.Error())232 oauthErrorReply(res, OAuthError{500, SERVER_ERROR, "Internal Server Error"})233 return234 }235 res.Header().Set("Content-Type", "application/json;charset=UTF-8")236 res.Write(rt)237 return238 }239 oauthErrorReply(res, OAuthError{404, INVALID_REQUEST, "Invalid Endpoint"})240}241type dummyConnector struct{}242func (c dummyConnector) GetClient(key, secret string) (interface{}, error) {243 return nil, errors.New("GetClient is not implemented")244}245func (c dummyConnector) GetUserFromAccessToken(accessToken string) (interface{}, error) {246 return nil, errors.New("GetUserFromAccessToken is not implemented")247}248func (c dummyConnector) AuthenticateUser(username, password string) (interface{}, error) {249 return nil, errors.New("AuthenticateUser is not implemented")250}251func (c dummyConnector) GetAccessToken(user, client interface{}) (JSONAble, error) {252 return nil, errors.New("GetAccessToken is not implemented")253}254func init() {255 log.SetLevel(log.DebugLevel)256 SetConnector(dummyConnector{})257}...

Full Screen

Full Screen

no-server.go

Source:no-server.go Github

copy

Full Screen

...31 }32 // if all constructor options failed, returned errors returned by each option33 return nil, stacktrace.Propagate(merr, "all options failed with errors:")34}35type AuthenticateUserOption func(*AuthenticateUserFuncConfig) error36type AuthenticateUserFuncConfig struct {37 userLoginHint string38}39func WithUserLoginHint(loginHint string) AuthenticateUserOption {40 return func(config *AuthenticateUserFuncConfig) error {41 config.userLoginHint = loginHint42 return nil43 }44}45// AuthenticateUser() option creates a new http.Client with a bearer access token46func AuthenticateUser(oauthConfig *oauth2.Config, options ...AuthenticateUserOption) ClientConstructorOption {47 var funcConfig AuthenticateUserFuncConfig48 for _, optionFunc := range options {49 optionFunc(&funcConfig)50 }51 // apply oauth2ns options52 var oauth2nsOptions []oauth2ns.AuthenticateUserOption53 if funcConfig.userLoginHint != "" {54 var urlValues = url.Values{}55 urlValues.Set("login_hint", funcConfig.userLoginHint)56 oauth2nsOptions = append(oauth2nsOptions, oauth2ns.WithAuthCallHTTPParams(urlValues))57 }58 return func() (*AuthorizedClient, error) {59 authorizedClient, err := oauth2ns.AuthenticateUser(oauthConfig, oauth2nsOptions...)60 if err != nil {61 return nil, stacktrace.Propagate(err, "failed authenticating user")62 }63 return (*AuthorizedClient)(authorizedClient), nil64 }65}66func FromToken(oauthConfig *oauth2.Config, token *oauth2.Token) ClientConstructorOption {67 return func() (*AuthorizedClient, error) {68 return &AuthorizedClient{69 Client: oauthConfig.Client(context.Background(), token),70 Token: token,71 }, nil72 }73}...

Full Screen

Full Screen

oauth.go

Source:oauth.go Github

copy

Full Screen

...36}37func OauthSigningKey() []byte {38 return []byte(os.Getenv("OAUTH_CLIENT_SIGNING_KEY"))39}40// AuthenticateUser authes the user & gets a new github client41func AuthenticateUser(tokenStr string) *github.Client {42 token, _ := tokenFromJSON(tokenStr)43 oauthClient := OauthConf().Client(oauth2.NoContext, token)44 client := github.NewClient(oauthClient)45 return client46}47func GetUserFromCookie(cookie *http.Cookie) (*authUser, error) {48 return decodeJWT(cookie.Value)49}50func decodeJWT(tokenStr string) (*authUser, error) {51 token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {52 if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {53 return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])54 }55 return OauthSigningKey(), nil...

Full Screen

Full Screen

AuthenticateUser

Using AI Code Generation

copy

Full Screen

1import (2func init() {3 orm.RegisterDriver("mysql", orm.DRMySQL)4 orm.RegisterDataBase("default", "mysql", "root:root@/test?charset=utf8")5 orm.RegisterModel(new(User))6}7type User struct {8}9type MainController struct {10}11func (this *MainController) Get() {

Full Screen

Full Screen

AuthenticateUser

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Hello, world.")4}5import "fmt"6func main() {7 fmt.Println("Hello, world.")8}9import "fmt"10func main() {11 fmt.Println("Hello, world.")12}13import "fmt"14func main() {15 fmt.Println("Hello, world.")16}17import "fmt"18func main() {19 fmt.Println("Hello, world.")20}21import "fmt"22func main() {23 fmt.Println("Hello, world.")24}25import "fmt"26func main() {27 fmt.Println("Hello, world.")28}29import "fmt"30func main() {31 fmt.Println("Hello, world.")32}33import "fmt"34func main() {35 fmt.Println("Hello, world.")36}37import "fmt"38func main() {39 fmt.Println("Hello, world.")40}

Full Screen

Full Screen

AuthenticateUser

Using AI Code Generation

copy

Full Screen

1import (2type Oauth struct {3}4func (o *Oauth) AuthenticateUser() {5 fmt.Println("Authenticate User")6}7func main() {8 o := new(Oauth)9 o.AuthenticateUser()10}11import (12type Oauth struct {13}14func (o *Oauth) AuthenticateUser() {15 fmt.Println("Authenticate User")16}17func main() {18 o := new(Oauth)19 o.AuthenticateUser()20}21import (22type Oauth struct {23}24func (o *Oauth) AuthenticateUser() {25 fmt.Println("Authenticate User")26}27func main() {28 o := new(Oauth)29 o.AuthenticateUser()30}31import (32type Oauth struct {33}34func (o *Oauth) AuthenticateUser() {35 fmt.Println("Authenticate User")36}37func main() {38 o := new(Oauth)39 o.AuthenticateUser()40}41import (42type Oauth struct {43}44func (o *Oauth) AuthenticateUser() {45 fmt.Println("Authenticate User")46}47func main() {48 o := new(Oauth)49 o.AuthenticateUser()50}51import (52type Oauth struct {53}54func (o *Oauth) AuthenticateUser() {55 fmt.Println("Authenticate User")56}57func main() {58 o := new(Oauth)59 o.AuthenticateUser()60}61import (62type Oauth struct {63}64func (o *Oauth) AuthenticateUser() {65 fmt.Println("Authenticate User")66}67func main() {68 o := new(Oauth)69 o.AuthenticateUser()70}71import (72type Oauth struct {73}74func (o *Oauth) AuthenticateUser() {75 fmt.Println("Authenticate User")76}77func main() {78 o := new(Oauth)79 o.AuthenticateUser()80}81import (

Full Screen

Full Screen

AuthenticateUser

Using AI Code Generation

copy

Full Screen

1func main() {2 oauth := new(OAuth)3 oauth.AuthenticateUser()4}5func main() {6 oauth := new(OAuth)7 oauth.AuthenticateUser()8}9func main() {10 oauth := new(OAuth)11 oauth.AuthenticateUser()12}13func main() {14 oauth := new(OAuth)15 oauth.AuthenticateUser()16}17func main() {18 oauth := new(OAuth)19 oauth.AuthenticateUser()20}21func main() {22 oauth := new(OAuth)23 oauth.AuthenticateUser()24}25func main() {26 oauth := new(OAuth)27 oauth.AuthenticateUser()28}29func main() {30 oauth := new(OAuth)31 oauth.AuthenticateUser()32}33func main() {34 oauth := new(OAuth)35 oauth.AuthenticateUser()36}37func main() {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful