예제 #1
0
파일: __init__.py 프로젝트: 90era/passport
def GitHub_Login_Page_State(code,
                            GITHUB_APP_ID,
                            GITHUB_APP_KEY,
                            GITHUB_REDIRECT_URI,
                            timeout=5,
                            verify=False):
    ''' Authorization Code cannot repeat '''
    Access_Token_Url = Splice(scheme="https",
                              domain="github.com",
                              path="/login/oauth/access_token",
                              query={
                                  "client_id": GITHUB_APP_ID,
                                  "client_secret": GITHUB_APP_KEY,
                                  "code": code,
                                  "redirect_uri": GITHUB_REDIRECT_URI
                              }).geturl
    data = requests.post(Access_Token_Url, timeout=timeout, verify=verify).text
    data = Parse_Access_Token(data)

    if "access_token" in data:
        access_token = data.get("access_token")
        User_Info_Url = Splice(scheme="https",
                               domain="api.github.com",
                               path="/user",
                               query={
                                   "access_token": access_token
                               }).geturl
        data = requests.get(User_Info_Url, timeout=timeout,
                            verify=verify).json()
        username = "******" + data.get("login")
        user_id = data.get("id")
        user_github = data.get("html_url")
        user_cname = data.get("name")
        user_avater = data.get("avatar_url")
        user_email = data.get("email")
        user_extra = "blog:%s, company:%s, location:%s" % (
            data.get("blog"), data.get("company"), data.get("location"))
        try:
            UserSQL = "INSERT INTO User (username, cname, email, avatar, time, github, extra) VALUES (%s, %s, %s, %s, %s, %s, %s)"
            mysql.insert(UserSQL, username, user_cname, user_email,
                         user_avater, How_Much_Time(), user_github, user_extra)
            OAuthSQL = "INSERT INTO OAuth (oauth_username, oauth_type, oauth_openid, oauth_access_token, oauth_expires) VALUES (%s, %s, %s, %s, %s)"
            mysql.insert(OAuthSQL, username, "GitHub", user_id, access_token,
                         How_Much_Time())
        except IntegrityError, e:
            logger.debug(e, exc_info=True)
            #Check if it has been registered
            CheckSQL = "SELECT oauth_username FROM OAuth WHERE oauth_username=%s"
            if mysql.get(CheckSQL, username):
                UpdateSQL = "UPDATE OAuth SET oauth_access_token=%s, oauth_expires=%s, oauth_openid=%s WHERE oauth_username=%s"
                mysql.update(UpdateSQL, access_token, How_Much_Time(), user_id,
                             username)
                #update user profile
                UpdateUserSQL = "UPDATE User SET cname=%s, avatar=%s, extra=%s WHERE username=%s"
                mysql.update(UpdateUserSQL, user_cname, user_avater,
                             user_extra, username)
                return {"username": username, "uid": user_id}
        except Exception, e:
            logger.error(e, exc_info=True)
            return False
예제 #2
0
파일: __init__.py 프로젝트: 90era/passport
    def get(self):

        code = request.args.get("code")
        SSORequest = True if request.args.get("sso") in ("true", "True", True,
                                                         "1", "on") else False
        SSOProject = request.args.get("sso_p")
        SSORedirect = request.args.get("sso_r")
        SSOToken = request.args.get("sso_t")
        SSOTokenMD5 = md5("%s:%s" % (SSOProject, SSORedirect))
        logger.debug(request.args)
        logger.debug(SSOTokenMD5 == SSOToken)
        if g.signin:
            return redirect(url_for("uc"))
        elif code:
            SSOLoginURL = "%s?%s" % (
                PLUGINS['thirdLogin']['GITHUB']['REDIRECT_URI'],
                urlencode({
                    "sso": SSORequest,
                    "sso_r": SSORedirect,
                    "sso_p": SSOProject,
                    "sso_t": SSOToken
                }))
            logger.debug(SSOLoginURL)
            data = GitHub_Login_Page_State(
                code, PLUGINS['thirdLogin']['GITHUB']['APP_ID'],
                PLUGINS['thirdLogin']['GITHUB']['APP_KEY'], SSOLoginURL)
            if data:
                username = data.get("username")
                expires_in = 3600 * 24 * 30
                userid = data.get("uid")
                expire_time = How_Much_Time(
                    seconds=expires_in) if expires_in else None
                sessionId = md5(
                    '%s-%s-%s-%s' %
                    (username, userid, expire_time, "COOKIE_KEY")).upper()
                if SSOProject in GLOBAL.get(
                        "ACL"
                ) and SSORequest and SSORedirect and SSOTokenMD5 == SSOToken:
                    logger.info(
                        "RequestURL:%s, SSORequest:%s, SSOProject:%s, SSORedirect:%s"
                        % (request.url, SSORequest, SSOProject, SSORedirect))
                    ticket = '.'.join([username, expire_time, sessionId])
                    returnURL = SSORedirect + "?ticket=" + ticket
                    logger.info(
                        "SSO(%s) request project is in acl, will create a ticket, redirect to %s"
                        % (SSOProject, returnURL))
                    resp = make_response(redirect(returnURL))
                else:
                    logger.info("Not SSO Auth, to local auth")
                    resp = make_response(redirect(url_for("uc")))
                resp.set_cookie(key='logged_in',
                                value="yes",
                                max_age=expires_in)
                resp.set_cookie(key='username',
                                value=username,
                                max_age=expires_in)
                resp.set_cookie(key='time',
                                value=expire_time,
                                max_age=expires_in)
                resp.set_cookie(key='Azone',
                                value="GitHub",
                                max_age=expires_in)
                resp.set_cookie(
                    key='sessionId',
                    value=md5(
                        '%s-%s-%s-%s' %
                        (username, userid, expire_time, "COOKIE_KEY")).upper(),
                    max_age=expires_in)
                return resp
        else:
            return redirect(url_for("login"))
예제 #3
0
파일: __init__.py 프로젝트: 90era/passport
def Weibo_Login_Page_State(code,
                           WEIBO_APP_ID,
                           WEIBO_APP_KEY,
                           WEIBO_REDIRECT_URI,
                           timeout=5,
                           verify=False):
    ''' Authorization Code cannot repeat '''
    Access_Token_Url = Splice(scheme="https",
                              domain="api.weibo.com",
                              path="/oauth2/access_token",
                              query={
                                  "grant_type": "authorization_code",
                                  "client_id": WEIBO_APP_ID,
                                  "client_secret": WEIBO_APP_KEY,
                                  "code": code,
                                  "redirect_uri": WEIBO_REDIRECT_URI
                              }).geturl
    data = requests.post(Access_Token_Url, timeout=timeout,
                         verify=verify).json()
    if "access_token" in data:
        access_token = data.get("access_token")
        expires_in = data.get("expires_in")
        uid = requests.get(
            "https://api.weibo.com/2/account/get_uid.json?access_token=%s" %
            access_token,
            timeout=timeout,
            verify=verify).json().get("uid", data.get("uid"))
        User_Info_Url = Splice(scheme="https",
                               domain="api.weibo.com",
                               path="/2/users/show.json",
                               query={
                                   "access_token": access_token,
                                   "uid": uid
                               }).geturl
        data = requests.get(User_Info_Url, timeout=timeout,
                            verify=verify).json()
        logger.debug(data)
        username = "******" + access_token[4:13]
        user_cname = data.get("screen_name")
        user_avater = data.get("profile_image_url")
        user_weibo = "http://weibo.com/" + data.get("profile_url")
        user_extra = data.get("description")
        user_gender = u"男" if data.get("gender") == "m" else u"女"
        try:
            UserSQL = "INSERT INTO User (username, cname, avatar, time, weibo, gender, extra) VALUES (%s, %s, %s, %s, %s, %s, %s)"
            mysql.insert(UserSQL, username, user_cname, user_avater,
                         How_Much_Time(), user_weibo, user_gender, user_extra)
            OAuthSQL = "INSERT INTO OAuth (oauth_username, oauth_type, oauth_openid, oauth_access_token, oauth_expires) VALUES (%s, %s, %s, %s, %s)"
            mysql.insert(OAuthSQL, username, "Weibo", uid, access_token,
                         How_Much_Time(seconds=int(expires_in)))
        except IntegrityError, e:
            logger.debug(e, exc_info=True)
            #Check if it has been registered
            CheckSQL = "SELECT oauth_username FROM OAuth WHERE oauth_username=%s"
            if mysql.get(CheckSQL, username):
                UpdateSQL = "UPDATE OAuth SET oauth_access_token=%s, oauth_expires=%s, oauth_openid=%s WHERE oauth_username=%s"
                mysql.update(UpdateSQL, access_token,
                             How_Much_Time(seconds=int(expires_in)), uid,
                             username)
                #update user profile
                UpdateUserSQL = "UPDATE User SET cname=%s, avatar=%s, weibo=%s, gender=%s, extra=%s WHERE username=%s"
                mysql.update(UpdateUserSQL, user_cname, user_avater,
                             user_weibo, user_gender, user_extra, username)
                return {
                    "username": username,
                    "expires_in": expires_in,
                    "uid": uid
                }
        except Exception, e:
            logger.error(e, exc_info=True)
            return False
예제 #4
0
파일: __init__.py 프로젝트: 90era/passport
                            "access_token": access_token,
                            "oauth_consumer_key": QQ_APP_ID,
                            "openid": openid
                        }).geturl
 UserQzoneInfo = requests.get(User_Info_Url,
                              timeout=timeout,
                              verify=verify).json()
 username = "******" + openid[:9]
 user_extra = "%s %s" % (UserQzoneInfo.get("province"),
                         UserQzoneInfo.get("city"))
 logger.info(UserQzoneInfo)
 try:
     UserSQL = "INSERT INTO User (username, cname, avatar, time, gender, extra) VALUES (%s, %s, %s, %s, %s, %s)"
     mysql.insert(UserSQL, username, UserQzoneInfo.get("nickname"),
                  UserQzoneInfo.get("figureurl_qq_1"),
                  How_Much_Time(), UserQzoneInfo.get("gender"),
                  user_extra)
     OAuthSQL = "INSERT INTO OAuth (oauth_username, oauth_type, oauth_openid, oauth_access_token, oauth_expires) VALUES (%s, %s, %s, %s, %s)"
     mysql.insert(OAuthSQL, username, "QQ", openid, access_token,
                  How_Much_Time(seconds=int(expires_in)))
 except IntegrityError, e:
     logger.debug(e, exc_info=True)
     #Check if it has been registered
     CheckSQL = "SELECT oauth_username FROM OAuth WHERE oauth_username=%s"
     if mysql.get(CheckSQL, username):
         UpdateSQL = "UPDATE OAuth SET oauth_access_token=%s, oauth_expires=%s WHERE oauth_username=%s"
         mysql.update(UpdateSQL, access_token,
                      How_Much_Time(seconds=int(expires_in)),
                      username)
         #update user profile
         UpdateUserSQL = "UPDATE User SET cname=%s,gender=%s,extra=%s WHERE username=%s"
예제 #5
0
def login():
    SSORequest = True if request.args.get("sso") in ("true", "True", True, "1",
                                                     "on") else False
    SSOProject = request.args.get("sso_p")
    SSORedirect = request.args.get("sso_r")
    SSOToken = request.args.get("sso_t")
    SSOTokenMD5 = md5("%s:%s" % (SSOProject, SSORedirect))
    logger.debug(request.args)
    logger.debug("remember: %s" % request.form)
    logger.debug(SSOTokenMD5 == SSOToken)
    if g.signin:
        if SSOProject in GLOBAL.get(
                "ACL"
        ) and SSORequest and SSORedirect and SSOTokenMD5 == SSOToken:
            returnURL = SSORedirect + "?ticket=" + g.credential
            logger.info(
                "SSO(%s) request project is in acl, already landing, redirect to %s"
                % (SSOProject, returnURL))
            return redirect(returnURL)
        else:
            return redirect(url_for("uc"))
    else:
        if request.method == "GET":
            return render_template(
                "signin.html",
                enable_qq=PLUGINS['thirdLogin']['QQ']['ENABLE'],
                enable_weibo=PLUGINS['thirdLogin']['WEIBO']['ENABLE'],
                enable_github=PLUGINS['thirdLogin']['GITHUB']['ENABLE'],
                enable_instagram=PLUGINS['thirdLogin']['INSTAGRAM']['ENABLE'],
                enable_oschina=PLUGINS['thirdLogin']['OSCHINA']['ENABLE'])
        else:
            username = request.form.get("username")
            password = request.form.get("password")
            remember = 30 if request.form.get("remember") in ("True", "true",
                                                              True) else None
            if username and password and UserAuth_Login(username, password):
                max_age_sec = 3600 * 24 * remember if remember else None
                expires = How_Much_Time(max_age_sec) if max_age_sec else 'None'
                #expire_time = datetime.datetime.today() + datetime.timedelta(days=remember) if remember else None
                sessionId = md5(
                    '%s-%s-%s-%s' %
                    (username, md5(password), expires, "COOKIE_KEY")).upper()
                logger.debug(
                    "check user login successful, max_age_sec: %s, expires: %s"
                    % (max_age_sec, expires))
                if SSOProject in GLOBAL.get(
                        "ACL"
                ) and SSORequest and SSORedirect and SSOTokenMD5 == SSOToken:
                    logger.info(
                        "RequestURL:%s, SSORequest:%s, SSOProject:%s, SSORedirect:%s"
                        % (request.url, SSORequest, SSOProject, SSORedirect))
                    ticket = '.'.join([username, expires, sessionId])
                    returnURL = SSORedirect + "?ticket=" + ticket
                    logger.info(
                        "SSO(%s) request project is in acl, will create a ticket, redirect to %s"
                        % (SSOProject, returnURL))
                    resp = make_response(redirect(returnURL))
                else:
                    logger.info("Not SSO Auth, to local auth")
                    resp = make_response(redirect(url_for("uc")))
                resp.set_cookie(key='logged_in',
                                value="yes",
                                max_age=max_age_sec)
                resp.set_cookie(key='username',
                                value=username,
                                max_age=max_age_sec)
                resp.set_cookie(key='sessionId',
                                value=sessionId,
                                max_age=max_age_sec)
                resp.set_cookie(key='time', value=expires, max_age=max_age_sec)
                resp.set_cookie(key='Azone',
                                value="local",
                                max_age=max_age_sec)
                #LogonCredentials: make_signed_cookie(username, md5(password), seconds=max_age_sec)
                #LogonCredentials: make_signed_cookie(username, openid/uid, seconds=max_age_sec)
                return resp
            else:
                if SSORequest:
                    return redirect(
                        url_for("login",
                                sso=SSORequest,
                                sso_p=SSOProject,
                                sso_r=SSORedirect,
                                sso_t=SSOToken))
                else:
                    return redirect(url_for("login"))
예제 #6
0
def OSChina_Login_Page_State(code,
                             OSCHINA_APP_ID,
                             OSCHINA_APP_KEY,
                             OSCHINA_REDIRECT_URI,
                             timeout=5,
                             verify=False):
    ''' Authorization Code cannot repeat '''
    Access_Token_Url = Splice(scheme="https",
                              netloc="www.oschina.net",
                              path="/action/openapi/token",
                              query={
                                  "grant_type": "authorization_code",
                                  "client_id": OSCHINA_APP_ID,
                                  "client_secret": OSCHINA_APP_KEY,
                                  "code": code,
                                  "redirect_uri": OSCHINA_REDIRECT_URI
                              }).geturl
    data = requests.post(Access_Token_Url,
                         timeout=timeout,
                         verify=verify,
                         headers=headers).json()
    if "access_token" in data:
        access_token = data.get("access_token")
        refresh_token = data.get("refresh_token")
        expires_in = data.get("expires_in")
        uid = data.get("uid")
        User_Info_Url = Splice(scheme="https",
                               netloc="www.oschina.net/",
                               path="/action/openapi/user",
                               query={
                                   "access_token": access_token
                               }).geturl
        data = requests.get(User_Info_Url,
                            timeout=timeout,
                            verify=verify,
                            headers=headers).json()
        logger.debug(data)
        username = "******" + access_token[4:13]
        user_cname = data.get("name")
        user_avater = data.get("avatar")
        user_extra = data.get("location")
        user_gender = u"男" if data.get("gender") == "male" else u"女"
        user_url = data.get("url")
        try:
            UserSQL = "INSERT INTO user_profile (username, cname, avatar, time, url, gender, extra) VALUES (%s, %s, %s, %s, %s, %s, %s)"
            mysql.insert(UserSQL, username, user_cname, user_avater,
                         How_Much_Time(), user_url, user_gender, user_extra)
            OAuthSQL = "INSERT INTO user_oauth (oauth_username, oauth_type, oauth_openid, oauth_access_token, oauth_expires) VALUES (%s, %s, %s, %s, %s)"
            mysql.insert(OAuthSQL, username, "OSChina", uid, access_token,
                         How_Much_Time(seconds=int(expires_in)))
        except IntegrityError, e:
            logger.debug(e, exc_info=True)
            #Check if it has been registered
            CheckSQL = "SELECT oauth_username FROM user_oauth WHERE oauth_username=%s"
            if mysql.get(CheckSQL, username):
                UpdateSQL = "UPDATE user_oauth SET oauth_access_token=%s, oauth_expires=%s, oauth_openid=%s WHERE oauth_username=%s"
                mysql.update(UpdateSQL, access_token,
                             How_Much_Time(seconds=int(expires_in)), uid,
                             username)
                #update user profile
                UpdateUserSQL = "UPDATE user_profile SET cname=%s, url=%s, gender=%s, extra=%s WHERE username=%s"
                mysql.update(UpdateUserSQL, user_cname, user_url, user_gender,
                             user_extra, username)
                return {
                    "username": username,
                    "expires_in": expires_in,
                    "uid": uid
                }
        except Exception, e:
            logger.error(e, exc_info=True)
            return False
예제 #7
0
def Instagram_Login_Page_State(code,
                               INSTAGRAM_APP_ID,
                               INSTAGRAM_APP_KEY,
                               INSTAGRAM_REDIRECT_URI,
                               timeout=5,
                               verify=False):
    ''' Authorization Code cannot repeat '''
    proxies = {
        "http": "http://ip:port",
        "https": "http://ip:port",
    }
    Access_Token_Url = Splice(scheme="https",
                              netloc="api.instagram.com",
                              path="/oauth/access_token",
                              query={
                                  "client_id": INSTAGRAM_APP_ID,
                                  "client_secret": INSTAGRAM_APP_KEY,
                                  "code": code,
                                  "redirect_uri": INSTAGRAM_REDIRECT_URI,
                                  "grant_type": "authorization_code"
                              }).geturl
    logger.debug(Access_Token_Url)
    data = requests.post(Access_Token_Url,
                         timeout=timeout,
                         verify=verify,
                         proxies=proxies).json()

    if "access_token" in data:
        access_token = data.get("access_token")
        data = requests.get(User_Info_Url,
                            timeout=timeout,
                            verify=verify,
                            proxies=proxies).json()
        User_Info_Url = Splice(scheme="https",
                               netloc="api.instagram.com",
                               path="/v1/users/self/",
                               query={
                                   "access_token": access_token
                               }).geturl
        data = requests.get(User_Info_Url,
                            timeout=timeout,
                            verify=verify,
                            proxies=proxies).json()
        username = "******" + data.get("username")
        user_id = data.get("id")
        user_cname = data.get("full_name")
        user_avater = data.get("profile_picture")
        user_url = data.get("website")
        user_motto = data.get("bio")
        user_extra = data.get("counts")
        try:
            UserSQL = "INSERT INTO user_profile (username, cname, motto, avatar, time, url, extra) VALUES (%s, %s, %s, %s, %s, %s, %s)"
            mysql.insert(UserSQL, username, user_cname, user_motto,
                         user_avater, How_Much_Time(), user_url, user_extra)
            OAuthSQL = "INSERT INTO user_oauth (oauth_username, oauth_type, oauth_openid, oauth_access_token, oauth_expires) VALUES (%s, %s, %s, %s, %s)"
            mysql.insert(OAuthSQL, username, "Instagram", user_id,
                         access_token, How_Much_Time())
        except IntegrityError, e:
            logger.debug(e, exc_info=True)
            #Check if it has been registered
            CheckSQL = "SELECT oauth_username FROM user_oauth WHERE oauth_username=%s"
            if mysql.get(CheckSQL, username):
                UpdateSQL = "UPDATE user_oauth SET oauth_access_token=%s, oauth_expires=%s, oauth_openid=%s WHERE oauth_username=%s"
                mysql.update(UpdateSQL, access_token, How_Much_Time(), user_id,
                             username)
                #update user profile
                UpdateUserSQL = "UPDATE user_profile SET cname=%s, url=%s, motto=%s, extra=%s WHERE username=%s"
                mysql.update(UpdateUserSQL, user_cname, user_url, user_motto,
                             user_extra, username)
                return {"username": username, "uid": user_id}
        except Exception, e:
            logger.error(e, exc_info=True)
            return False