2021-03-13 23:06:03 +08:00
// Copyright 2021 The casbin Authors. All Rights Reserved.
2021-02-14 00:22:24 +08:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
2021-03-15 00:49:16 +08:00
"encoding/json"
2021-02-14 00:22:24 +08:00
"fmt"
2021-06-11 23:34:45 +08:00
"strconv"
2021-06-02 13:39:01 +08:00
"strings"
2021-02-14 00:22:24 +08:00
"github.com/astaxie/beego"
2021-02-21 22:33:53 +08:00
"github.com/casdoor/casdoor/idp"
2021-02-14 00:22:24 +08:00
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
2021-03-20 22:34:22 +08:00
func codeToResponse ( code * object . Code ) * Response {
if code . Code == "" {
return & Response { Status : "error" , Msg : code . Message , Data : code . Code }
} else {
return & Response { Status : "ok" , Msg : "" , Data : code . Code }
}
}
2021-06-20 22:17:03 +08:00
func ( c * ApiController ) HandleLoggedIn ( application * object . Application , user * object . User , form * RequestForm ) * Response {
2021-05-01 19:45:40 +08:00
userId := user . GetId ( )
2021-03-20 10:51:00 +08:00
resp := & Response { }
if form . Type == ResponseTypeLogin {
c . SetSessionUser ( userId )
util . LogInfo ( c . Ctx , "API: [%s] signed in" , userId )
2021-03-20 13:05:34 +08:00
resp = & Response { Status : "ok" , Msg : "" , Data : userId }
2021-03-20 10:51:00 +08:00
} else if form . Type == ResponseTypeCode {
clientId := c . Input ( ) . Get ( "clientId" )
responseType := c . Input ( ) . Get ( "responseType" )
redirectUri := c . Input ( ) . Get ( "redirectUri" )
scope := c . Input ( ) . Get ( "scope" )
state := c . Input ( ) . Get ( "state" )
code := object . GetOAuthCode ( userId , clientId , responseType , redirectUri , scope , state )
resp = codeToResponse ( code )
2021-06-20 22:17:03 +08:00
if application . HasPromptPage ( ) {
// The prompt page needs the user to be signed in
c . SetSessionUser ( userId )
}
2021-03-20 10:51:00 +08:00
} else {
2021-03-28 08:59:12 +08:00
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( "Unknown response type: %s" , form . Type ) }
2021-03-20 10:51:00 +08:00
}
return resp
}
2021-03-29 23:40:25 +08:00
// @Title GetApplicationLogin
// @Description get application login
// @Param clientId query string true "client id"
// @Param responseType query string true "response type"
// @Param redirectUri query string true "redirect uri"
// @Param scope query string true "scope"
// @Param state query string true "state"
// @Success 200 {object} controllers.api_controller.Response The Response object
// @router /update-application [get]
2021-03-20 10:51:00 +08:00
func ( c * ApiController ) GetApplicationLogin ( ) {
var resp Response
clientId := c . Input ( ) . Get ( "clientId" )
responseType := c . Input ( ) . Get ( "responseType" )
redirectUri := c . Input ( ) . Get ( "redirectUri" )
scope := c . Input ( ) . Get ( "scope" )
state := c . Input ( ) . Get ( "state" )
msg , application := object . CheckOAuthLogin ( clientId , responseType , redirectUri , scope , state )
if msg != "" {
resp = Response { Status : "error" , Msg : msg , Data : application }
} else {
resp = Response { Status : "ok" , Msg : "" , Data : application }
}
c . Data [ "json" ] = resp
c . ServeJSON ( )
2021-03-15 19:11:41 +08:00
}
2021-03-29 23:40:25 +08:00
// @Title Login
// @Description login
// @Param oAuthParams query string true "oAuth parameters"
// @Param body body RequestForm true "Login information"
// @Success 200 {object} controllers.api_controller.Response The Response object
// @router /login [post]
2021-03-20 00:23:37 +08:00
func ( c * ApiController ) Login ( ) {
2021-03-20 13:05:34 +08:00
resp := & Response { Status : "null" , Msg : "" }
2021-03-20 09:11:03 +08:00
var form RequestForm
2021-03-15 00:49:16 +08:00
err := json . Unmarshal ( c . Ctx . Input . RequestBody , & form )
if err != nil {
2021-06-09 19:54:26 +08:00
resp = & Response { Status : "error" , Msg : err . Error ( ) }
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
2021-03-15 00:49:16 +08:00
}
2021-02-14 00:22:24 +08:00
2021-03-20 00:23:37 +08:00
if form . Username != "" {
2021-03-20 13:05:34 +08:00
if form . Type == ResponseTypeLogin {
if c . GetSessionUser ( ) != "" {
2021-03-28 08:59:12 +08:00
resp = & Response { Status : "error" , Msg : "Please log out first before signing in" , Data : c . GetSessionUser ( ) }
2021-03-20 13:05:34 +08:00
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
}
2021-03-20 00:23:37 +08:00
}
2021-02-21 22:33:53 +08:00
2021-06-02 13:39:01 +08:00
var user * object . User
var msg string
if form . Password == "" {
var verificationCodeType string
// check result through Email or Phone
if strings . Contains ( form . Email , "@" ) {
verificationCodeType = "email"
checkResult := object . CheckVerificationCode ( form . Email , form . EmailCode )
if len ( checkResult ) != 0 {
responseText := fmt . Sprintf ( "Email%s" , checkResult )
c . ResponseError ( responseText )
return
}
} else {
verificationCodeType = "phone"
checkPhone := fmt . Sprintf ( "+%s%s" , form . PhonePrefix , form . Email )
checkResult := object . CheckVerificationCode ( checkPhone , form . EmailCode )
if len ( checkResult ) != 0 {
responseText := fmt . Sprintf ( "Phone%s" , checkResult )
c . ResponseError ( responseText )
return
}
}
// get user
var userId string
if form . Username == "" {
userId , _ = c . RequireSignedIn ( )
} else {
userId = fmt . Sprintf ( "%s/%s" , form . Organization , form . Username )
}
user = object . GetUser ( userId )
if user == nil {
c . ResponseError ( "No such user." )
return
}
// disable the verification code
switch verificationCodeType {
case "email" :
if user . Email != form . Email {
c . ResponseError ( "wrong email!" )
}
object . DisableVerificationCode ( form . Email )
break
case "phone" :
if user . Phone != form . Email {
c . ResponseError ( "wrong phone!" )
}
object . DisableVerificationCode ( form . Email )
break
}
} else {
password := form . Password
user , msg = object . CheckUserLogin ( form . Organization , form . Username , password )
}
2021-02-14 00:22:24 +08:00
2021-03-20 00:23:37 +08:00
if msg != "" {
2021-03-20 13:05:34 +08:00
resp = & Response { Status : "error" , Msg : msg , Data : "" }
2021-03-20 00:23:37 +08:00
} else {
2021-06-20 22:17:03 +08:00
application := object . GetApplication ( fmt . Sprintf ( "admin/%s" , form . Application ) )
resp = c . HandleLoggedIn ( application , user , & form )
2021-03-20 00:23:37 +08:00
}
} else if form . Provider != "" {
application := object . GetApplication ( fmt . Sprintf ( "admin/%s" , form . Application ) )
2021-06-21 01:01:16 +08:00
organization := object . GetOrganization ( fmt . Sprintf ( "%s/%s" , "admin" , application . Organization ) )
2021-03-20 00:23:37 +08:00
provider := object . GetProvider ( fmt . Sprintf ( "admin/%s" , form . Provider ) )
2021-06-14 21:35:19 +08:00
providerItem := application . GetProviderItem ( provider . Name )
2021-02-14 00:22:24 +08:00
2021-03-23 23:23:59 +08:00
idProvider := idp . GetIdProvider ( provider . Type , provider . ClientId , provider . ClientSecret , form . RedirectUri )
2021-06-06 11:17:37 +08:00
if idProvider == nil {
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( "provider: %s does not exist" , provider . Type ) }
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
}
2021-03-23 23:23:59 +08:00
idProvider . SetHttpClient ( httpClient )
2021-02-14 00:22:24 +08:00
2021-05-09 11:55:43 +08:00
if form . State != beego . AppConfig . String ( "authState" ) && form . State != application . Name {
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( "state expected: \"%s\", but got: \"%s\"" , beego . AppConfig . String ( "authState" ) , form . State ) }
2021-03-20 23:50:34 +08:00
c . Data [ "json" ] = resp
2021-03-20 00:23:37 +08:00
c . ServeJSON ( )
return
}
2021-02-14 00:22:24 +08:00
2021-03-20 00:23:37 +08:00
// https://github.com/golang/oauth2/issues/123#issuecomment-103715338
2021-03-23 23:23:59 +08:00
token , err := idProvider . GetToken ( form . Code )
2021-03-20 00:23:37 +08:00
if err != nil {
2021-03-25 23:22:34 +08:00
resp = & Response { Status : "error" , Msg : err . Error ( ) }
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
2021-03-20 00:23:37 +08:00
}
2021-02-14 00:22:24 +08:00
2021-03-20 00:23:37 +08:00
if ! token . Valid ( ) {
2021-03-28 08:59:12 +08:00
resp = & Response { Status : "error" , Msg : "Invalid token" }
2021-03-20 00:23:37 +08:00
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
2021-02-21 23:51:40 +08:00
}
2021-03-23 23:23:59 +08:00
userInfo , err := idProvider . GetUserInfo ( token )
2021-03-20 00:23:37 +08:00
if err != nil {
2021-03-28 08:59:12 +08:00
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( "Failed to login in: %s" , err . Error ( ) ) }
2021-03-20 00:23:37 +08:00
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
}
2021-02-21 23:51:40 +08:00
2021-03-20 00:23:37 +08:00
if form . Method == "signup" {
2021-05-31 00:55:29 +08:00
user := object . GetUserByField ( application . Organization , provider . Type , userInfo . Id )
2021-06-01 23:14:49 +08:00
if user == nil {
user = object . GetUserByField ( application . Organization , provider . Type , userInfo . Username )
}
2021-06-12 12:46:25 +08:00
if user == nil {
user = object . GetUserByField ( application . Organization , "name" , userInfo . Username )
}
2021-06-01 23:14:49 +08:00
2021-05-01 19:45:40 +08:00
if user != nil {
2021-06-14 21:35:19 +08:00
// Sign in via OAuth
2021-03-20 00:23:37 +08:00
//if object.IsForbidden(userId) {
// c.forbiddenAccountResp(userId)
// return
//}
2021-02-21 23:51:40 +08:00
2021-03-20 00:23:37 +08:00
//if len(object.GetMemberAvatar(userId)) == 0 {
// avatar := UploadAvatarToOSS(res.Avatar, userId)
// object.LinkMemberAccount(userId, "avatar", avatar)
//}
2021-02-21 23:51:40 +08:00
2021-06-20 22:17:03 +08:00
resp = c . HandleLoggedIn ( application , user , & form )
2021-03-20 00:23:37 +08:00
} else {
2021-06-14 21:35:19 +08:00
// Sign up via OAuth
if ! application . EnableSignUp {
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( "The account for provider: %s and username: %s (%s) does not exist and is not allowed to sign up as new account, please contact your IT support" , provider . Type , userInfo . Username , userInfo . DisplayName ) }
2021-03-26 21:55:39 +08:00
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
2021-06-14 21:35:19 +08:00
}
if ! providerItem . CanSignUp {
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( "The account for provider: %s and username: %s (%s) does not exist and is not allowed to sign up as new account via %s, please use another way to sign up" , provider . Type , userInfo . Username , userInfo . DisplayName , provider . Type ) }
2021-03-26 21:55:39 +08:00
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
2021-02-21 23:51:40 +08:00
}
2021-06-14 21:35:19 +08:00
properties := map [ string ] string { }
properties [ "no" ] = strconv . Itoa ( len ( object . GetUsers ( application . Organization ) ) + 2 )
user := & object . User {
Owner : application . Organization ,
Name : userInfo . Username ,
CreatedTime : util . GetCurrentTime ( ) ,
Id : util . GenerateId ( ) ,
Type : "normal-user" ,
DisplayName : userInfo . DisplayName ,
Avatar : userInfo . AvatarUrl ,
Email : userInfo . Email ,
Score : 200 ,
IsAdmin : false ,
IsGlobalAdmin : false ,
IsForbidden : false ,
Properties : properties ,
}
object . AddUser ( user )
// sync info from 3rd-party if possible
2021-06-21 00:54:07 +08:00
object . SetUserOAuthProperties ( organization , user , provider . Type , userInfo )
2021-06-14 21:35:19 +08:00
object . LinkUserAccount ( user , provider . Type , userInfo . Id )
2021-06-20 22:17:03 +08:00
resp = c . HandleLoggedIn ( application , user , & form )
2021-02-14 00:22:24 +08:00
}
2021-03-20 13:05:34 +08:00
//resp = &Response{Status: "ok", Msg: "", Data: res}
2021-06-09 21:27:20 +08:00
} else { // form.Method != "signup"
2021-03-20 00:23:37 +08:00
userId := c . GetSessionUser ( )
if userId == "" {
2021-03-28 08:59:12 +08:00
resp = & Response { Status : "error" , Msg : "The account does not exist" , Data : userInfo }
2021-03-20 00:23:37 +08:00
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
}
2021-06-18 23:25:24 +08:00
oldUser := object . GetUserByField ( application . Organization , provider . Type , userInfo . Id )
if oldUser == nil {
oldUser = object . GetUserByField ( application . Organization , provider . Type , userInfo . Username )
}
if oldUser != nil {
2021-06-20 09:46:06 +08:00
resp = & Response { Status : "error" , Msg : fmt . Sprintf ( "The account for provider: %s and username: %s (%s) is already linked to another account: %s (%s)" , provider . Type , userInfo . Username , userInfo . DisplayName , oldUser . Name , oldUser . DisplayName ) }
2021-06-18 23:25:24 +08:00
c . Data [ "json" ] = resp
c . ServeJSON ( )
return
}
2021-04-18 23:14:46 +08:00
user := object . GetUser ( userId )
2021-04-27 19:35:40 +08:00
// sync info from 3rd-party if possible
2021-06-21 00:54:07 +08:00
object . SetUserOAuthProperties ( organization , user , provider . Type , userInfo )
2021-04-27 19:35:40 +08:00
2021-05-31 00:55:29 +08:00
isLinked := object . LinkUserAccount ( user , provider . Type , userInfo . Id )
2021-03-24 00:11:20 +08:00
if isLinked {
resp = & Response { Status : "ok" , Msg : "" , Data : isLinked }
2021-03-20 00:23:37 +08:00
} else {
2021-03-28 08:59:12 +08:00
resp = & Response { Status : "error" , Msg : "Failed to link user account" , Data : isLinked }
2021-03-20 00:23:37 +08:00
}
//if len(object.GetMemberAvatar(userId)) == 0 {
// avatar := UploadAvatarToOSS(tempUserAccount.AvatarUrl, userId)
// object.LinkUserAccount(userId, "avatar", avatar)
//}
2021-02-14 00:22:24 +08:00
}
2021-03-20 00:23:37 +08:00
} else {
2021-04-29 13:50:29 +08:00
panic ( "unknown authentication type (not password or provider), form = " + util . StructToJson ( form ) )
2021-02-14 00:22:24 +08:00
}
c . Data [ "json" ] = resp
c . ServeJSON ( )
}