Skip to content

Commit

Permalink
added google authentification
Browse files Browse the repository at this point in the history
  • Loading branch information
feyruzb committed Jul 25, 2024
1 parent 3381a81 commit 68eaf7b
Show file tree
Hide file tree
Showing 11 changed files with 166 additions and 70 deletions.
6 changes: 5 additions & 1 deletion web/api/authentication.thrift
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ service codeCheckerAuthentication {
throws (1: codechecker_api_shared.RequestFailed requestError),

// Create a link for the user to log in for github Oauth.
string createLink()
string createLinkGithub()
throws (1: codechecker_api_shared.RequestFailed requestError),

// Create a link for the use to log in for google Oauth
string createLinkGoogle()
throws (1: codechecker_api_shared.RequestFailed requestError),

// Retrieves an OAuth token for the specified link.
Expand Down
Binary file modified web/api/js/codechecker-api-node/dist/codechecker-api-6.59.0.tgz
Binary file not shown.
Binary file modified web/api/py/codechecker_api/dist/codechecker_api.tar.gz
Binary file not shown.
Binary file not shown.
11 changes: 0 additions & 11 deletions web/client/codechecker_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,6 @@ def login_user(protocol, host, port, username, login=False):
LOG.error("Authentication failed! Please check your credentials.")
LOG.error(reqfail.message)
sys.exit(1)
elif 'oauth' in str(methods):
# GitHub app config
client_id = oauth_config['oauth_client_id']
client_secret = oauth_config['oauth_client_secret']
scope = oauth_config['oauth_scope']

# Create an OAuth2Session instance
url, _ = OAuth2Session(client_id, client_secret, scope=scope).create_authorization_url(oauth_config['oauth_authorization_url'])

return url
sys.exit(1)
else:
LOG.critical("No authentication methods were reported by the server "
"that this client could support.")
Expand Down
6 changes: 5 additions & 1 deletion web/client/codechecker_client/helpers/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ def performLogin(self, auth_method, auth_string):
pass

@ThriftClientCall
def createLink(self):
def createLinkGithub(self):
pass

@ThriftClientCall
def createLinkGoogle(self):
pass

@ThriftClientCall
Expand Down
79 changes: 53 additions & 26 deletions web/server/codechecker_server/api/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from ..server import permissions
from ..session_manager import generate_session_token

from authlib.common.security import generate_token

LOG = get_logger('server')

Expand All @@ -44,6 +45,7 @@ def __init__(self, manager, auth_session, config_database):
self.__auth_session = auth_session
self.__config_db = config_database
self.oauth_config_github = self.__manager.get_oauth_config("github")
self.oauth_config_google = self.__manager.get_oauth_config("google")

def __require_privilaged_access(self):
"""
Expand Down Expand Up @@ -96,7 +98,7 @@ def getLoggedInUser(self):
return ""

@timeit
def createLink(self):
def createLinkGithub(self):
"""
This functin is for creating a autehntication link for OAuth for Github.
"""
Expand All @@ -119,39 +121,34 @@ def createLink(self):
return url

@timeit
def getOAuthToken(self, link):
def createLinkGoogle(self):
"""
This function is for getting the OAuth token from the link for Oauth for Github.
This function is for creating an authentication link for OAuth for Google.
"""
oauth_config = self.auth_config.get("method_oauth", {})
oauth_config = self.oauth_config_google

if not oauth_config.get("enabled"):
raise codechecker_api_shared.ttypes.RequestFailed(
codechecker_api_shared.ttypes.ErrorCode.AUTH_DENIED,
"OAuth authentication is not enabled. 22")

client_id = oauth_config["oauth_client_id"] # may be changed
client_secret = oauth_config["oauth_client_secret"] # may be changed
scope = oauth_config["oauth_scope"] # may be changed
token_url = oauth_config["oauth_token_uri"] # may be changed
user_info_url = oauth_config["oauth_user_info_uri"] # may be changed

session = OAuth2Session(client_id, client_secret, scope=scope)
token = session.fetch_token(
url=token_url,
authorization_response=link,
)
user_info = session.get(user_info_url).json()
client_id = oauth_config["oauth_client_id"]
client_secret = oauth_config["oauth_client_secret"]
scope = oauth_config["oauth_scope"]
authorization_uri = oauth_config["oauth_authorization_uri"]
redirect_uri = oauth_config["oauth_redirect_uri"]
token_uri = oauth_config["oauth_token_uri"]


username = user_info[oauth_config["oauth_user_info_mapping"]["username"]]
email = user_info[oauth_config["oauth_user_info_mapping"]["email"]]
fullname = user_info[oauth_config["oauth_user_info_mapping"]["fullname"]]
# Create an OAuth2Session instance
session = OAuth2Session(client_id, client_secret, scope=scope, redirect_uri=redirect_uri)

if username not in oauth_config.get("allowed_users", []):
raise codechecker_api_shared.ttypes.RequestFailed(
codechecker_api_shared.ttypes.ErrorCode.AUTH_DENIED,
"User is not authorized to access this service.")
# Create authorization URL
nonce = generate_token()
authorization_url, state = session.create_authorization_url(authorization_uri, nonce=nonce)

return user_info

return authorization_url



Expand Down Expand Up @@ -231,7 +228,7 @@ def performLogin(self, auth_method, auth_string):
raise codechecker_api_shared.ttypes.RequestFailed(
codechecker_api_shared.ttypes.ErrorCode.AUTH_DENIED,
msg)
elif auth_method == "oauth":
elif auth_method == "oauth_github":
LOG.info("OAuth login... started")

oauth_config = self.oauth_config_github
Expand Down Expand Up @@ -263,7 +260,37 @@ def performLogin(self, auth_method, auth_string):
# return token
session = self.__manager.create_session("github@" + username + ":" + token['access_token'])
return session.token
# return self.__manager.create_session(username)
elif auth_method == "oauth_google":
LOG.info("OAuth login GOOGLE... started")

oauth_config = self.oauth_config_google
if not oauth_config.get("enabled"):
raise codechecker_api_shared.ttypes.RequestFailed(
codechecker_api_shared.ttypes.ErrorCode.AUTH_DENIED,
"OAuth authentication is not enabled.44")

client_id = oauth_config["oauth_client_id"]
client_secret = oauth_config["oauth_client_secret"]
scope = oauth_config["oauth_scope"]
token_url = oauth_config["oauth_token_uri"]
user_info_url = oauth_config["oauth_user_info_uri"]
redirect_uri = oauth_config["oauth_redirect_uri"]

session = OAuth2Session(client_id, client_secret, scope=scope, redirect_uri=redirect_uri)
token = session.fetch_token(
url=token_url,
authorization_response=f"{auth_string}",
)

user_info = session.get(user_info_url).json()
email = user_info[oauth_config["oauth_user_info_mapping"]["email"]]
if email not in oauth_config.get("allowed_users", []):
raise codechecker_api_shared.ttypes.RequestFailed(
codechecker_api_shared.ttypes.ErrorCode.AUTH_DENIED,
"User is not authorized to access this service.")

session = self.__manager.create_session("google@" + email + ":" + token['access_token'])
return session.token

raise codechecker_api_shared.ttypes.RequestFailed(
codechecker_api_shared.ttypes.ErrorCode.AUTH_DENIED,
Expand Down
15 changes: 13 additions & 2 deletions web/server/codechecker_server/session_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,8 @@ def __handle_validation(self, auth_string):
or self.__try_auth_dictionary(auth_string) \
or self.__try_auth_pam(auth_string) \
or self.__try_auth_ldap(auth_string) \
or self.__try_auth_oauth_github(auth_string)
or self.__try_auth_oauth_github(auth_string) \
or self.__try_auth_oauth_google(auth_string)
if not validation:
return False

Expand Down Expand Up @@ -506,12 +507,22 @@ def __try_auth_oauth_github(self, auth_string):
"""
Try to authenticate user based on the OAuth configuration.
"""
if self.__is_method_enabled('oauth'):
if self.__is_method_enabled('oauth') and 'github@' in auth_string:
data = auth_string.split('github@')[1]
username, token = data.split(':')

return {'username': username, 'token': token }

def __try_auth_oauth_google(self, auth_string):
"""
Try to authenticate user based on the OAuth configuration.
"""
if self.__is_method_enabled('oauth') and 'google@' in auth_string:
data = auth_string.split('google@')[1]
email, token = data.split(':')

return {'username': email, 'token': token }

def __update_groups(self, user_name, groups):
"""
Updates group field of the users tokens.
Expand Down
5 changes: 3 additions & 2 deletions web/server/vue-cli/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 35 additions & 14 deletions web/server/vue-cli/src/store/modules/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,32 @@ const actions = {
return new Promise((resolve, reject) => {

if (credentials.type === "oauth") {
authService.getClient().performLogin("oauth", credentials.url,
handleThriftError(token => {
context.commit(SET_AUTH, {
userName: "OAuth login",
token: token
});
resolve(token);
}, err => {
reject(err);
}));
return;
if (credentials.provider === "github") {
authService.getClient().performLogin("oauth_github", credentials.url,
handleThriftError(token => {
context.commit(SET_AUTH, {
userName: "OAuth login",
token: token
});
resolve(token);
}, err => {
reject(err);
}));
return;
}
else if (credentials.provider === "google") {
authService.getClient().performLogin("oauth_google", credentials.url,
handleThriftError(token => {
context.commit(SET_AUTH, {
userName: "OAuth login",
token: token
});
resolve(token);
}, err => {
reject(err);
}));
return;
}
}

authService.getClient().performLogin("Username:Password",
Expand All @@ -93,7 +108,7 @@ const actions = {
});
},

[LOGOUT](context) {
[LOGOUT](context) {
return new Promise((resolve, reject) => {
authService.getClient().destroySession(
handleThriftError(success => {
Expand All @@ -107,9 +122,15 @@ const actions = {
});
},

[OAUTH]() {
[OAUTH](provider) {
return new Promise(resolve => {
resolve(authService.getClient().createLink());
if (provider === "github") {
resolve(authService.getClient().createLinkGithub());
} else if (provider === "google") {
resolve(authService.getClient().createLinkGoogle());
} else {
throw new Error(`Unsupported provider: ${provider}`);
}
});
}
};
Expand Down
Loading

0 comments on commit 68eaf7b

Please sign in to comment.