Example #1
0
def refresh_token():
    rds = g.rds
    if not request.data:
        return INVALID_PARAM()

    obj = json.loads(request.data)
    refresh_token = obj["refresh_token"]

    uid = Token.load_refresh_token(rds, refresh_token)
    if not uid:
        return INVALID_REFRESH_TOKEN()

    access_token = gobelieve.login_gobelieve(int(uid), "")
        
    if not access_token:
        return CAN_NOT_GET_TOKEN()

    tok = {
        'expires_in': 3600,
        'token_type': 'Bearer',
        "access_token":access_token,
        "refresh_token":obj["refresh_token"],
        'uid':int(uid)
    }

    Token.save_access_token(g.rds, access_token, uid, 3600)
    
    return make_response(200, tok)
Example #2
0
 def create_admin_info_background(self, jsonInfo):
     '''
     创建管理员
     第一步:检查是否已经创建过(根据用户名或手机号);
     第二步:创建token
     第三步:创建admininfo
     :param jsonInfo: {'password': '', 'admin_name': '', 'tel': ''}
     :return: {'status': 'SUCCESS', 'data': ''}
     '''
     info = json.loads(jsonInfo)
     admin_name = info['admin_name']
     tel = info['tel']
     password = info['password']
     query = db.session.query(AdminInfo).filter(
         or_(AdminInfo.admin_name == admin_name,
             AdminInfo.tel == tel)
     )
     result = query.first()
     if result:
         return (False, ErrorInfo['WOLFS_02'])
     info['admin_id'] = self.generate_id(tel)
     info['password'] = self.get_md5_string(password)
     info['token_id'] = self.generate_id(info['admin_id'])
     info['user_id'] = info['admin_id']
     info['createtime'] = datetime.now()
     info['validity'] = VALIDITY
     Token.create(info=info)
     AdminInfo.create(info=info)
     db.session.commit()
     return (True, info['admin_id'])
Example #3
0
 def update_token(self, info):
     user_id = info['user_id']
     db.session.query(Token).filter(
         Token.user_id == user_id
     ).delete(synchronize_session=False)
     info = {}
     info['token_id'] = self.generate_id(user_id)
     info['user_id'] = user_id
     info['createtime'] = datetime.now()
     info['validity'] = VALIDITY
     Token.create(info=info)
     return (True, info['token_id'])
Example #4
0
def register_user():
    if not request.data:
        return INVALID_PARAM()
    
    req = json.loads(request.data)
    name = req.get('nickname')
    password = req.get('password')
    #短信验证码
    code = req.get("code")
    number = req.get("number")
    country_code = req.get("country_code")

    if not name or not password or not code \
       or not number or not country_code:
        return INVALID_PARAM()
    
    #check sms code
    if is_test_number(number):
        pass
    else:
        c2, timestamp, _ = code.get_verify_code(g.rds, country_code, number)
        if c1 != c2:
            return INVALID_CODE()
    password = generate_password_hash(password)
    phone_number = "+%s-%s"%(country_code, number)
    u = DBUser.get_user(g._db, phone_number)
    if u:
        uid = u['id']
        DBUser.save_user(g._db, uid, name, password)
    else:
        uid = DBUser.add_user(g._db, name, password, phone_number)

    #登录动作
    access_token = gobelieve.login_gobelieve(uid, name)
    if not access_token:
        return CAN_NOT_GET_TOKEN()

    tok = {
        'expires_in': 3600,
        "access_token":access_token,
        "refresh_token":random_token_generator(),
        'uid':uid
    }


    Token.save_access_token(g.rds, access_token, uid, 3600)
    Token.save_refresh_token(g.rds, tok['refresh_token'], uid)

    return make_response(200, tok)
Example #5
0
def access_token():
    if not request.data:
        return INVALID_PARAM()

    obj = json.loads(request.data)
    c1 = obj["code"]
    number = obj["number"]
    zone = obj["zone"]
    if is_test_number(number):
        pass
    else:
        c2, timestamp, _ = code.get_verify_code(g.rds, zone, number)
        if c1 != c2:
            return INVALID_CODE()

    uid = user.make_uid(zone, number)

    access_token = gobelieve.login_gobelieve(uid, "")
        
    if not access_token:
        return CAN_NOT_GET_TOKEN()

    u0 = user.get_user(g.rds, uid)
    u = user.User()
    u.uid = uid
    if u0 is None:
        u.state = "Hey!"
    else:
        u.state = u0.state

    user.save_user(g.rds, u)

    tok = {
        'expires_in': 3600,
        'token_type': 'Bearer',
        "access_token":access_token,
        "refresh_token":random_token_generator(),
        'uid':int(uid)
    }

    Token.save_access_token(g.rds, access_token, uid, 3600)
    Token.save_refresh_token(g.rds, tok['refresh_token'], uid)
    
    return make_response(200, tok)
Example #6
0
    def loginSession(self, session, rds):
        access_token = gobelieve.login_gobelieve(int(session.uid), "")
        if not access_token:
            raise Error(404, "imsdk can't login")

        tok = {
            'expires_in': TOKEN_EXPIRE,
            'token_type': 'Bearer',
            "access_token":access_token,
            "refresh_token":random_token_generator(),
            'uid':int(session.uid),
            'sid':session.sid
        }        
        Token.save_access_token(rds, access_token, int(session.uid), TOKEN_EXPIRE)
        session.expire(rds, TOKEN_EXPIRE)
        
        web.setcookie("sid", session.sid, TOKEN_EXPIRE)
        web.setcookie("token", access_token, TOKEN_EXPIRE)
        return json.dumps(tok)
Example #7
0
def login():
    if not request.data:
        return INVALID_PARAM()
    
    req = json.loads(request.data)

    password = req.get('password')
    number = req.get("number")
    country_code = req.get("country_code")

    phone_number = "+%s-%s"%(country_code, number)
    u = DBUser.get_user(g._db, phone_number)
    if not u:
        return INVALID_USERNAME()
    if not check_password_hash(u['password'], password):
        return INVALID_PASSWORD()

    uid = u['id']
    nickname = u.get('nickname')
    avatar = u.get('avatar')
    state = u.get('state')
    nickname = nickname if nickname else ""
    avatar = avatar if avatar else ""
    state = state if state else ""
    
    access_token = gobelieve.login_gobelieve(uid, nickname)
        
    if not access_token:
        return CAN_NOT_GET_TOKEN()

    tok = {
        'expires_in': 3600,
        "access_token":access_token,
        "refresh_token":random_token_generator(),
        'uid':u['id'],
        'avatar':avatar,
        'state':state
    }

    Token.save_access_token(g.rds, access_token, u['id'], 3600)
    Token.save_refresh_token(g.rds, tok['refresh_token'], u['id'])
    
    return make_response(200, tok)
Example #8
0
 def create_user_background(self, info):
     '''
     后台,创建用户
     第一步: 验证管理员身份
     第二步: 创建Token, Imgpath, UserInfo信息
     :param info: {'token_id': '', 'user_name': '', 'imgpath': '', 'user_id': '', 'open_id': ''}
     :return: {'data': '', 'status': 'SUCCESS'}
     '''
     info['user_id'] = self.generate_id(info['user_name'])
     info['token_id'] = self.generate_id(info['user_id'])
     info['createtime'] = datetime.now()
     info['validity'] = VALIDITY
     Token.create(info)
     info['imgpath_id'] = self.generate_id(info['imgpath'])
     info['imgpath'] = info['imgpath']
     info['foreign_id'] = info['user_id']
     ImgPath.create(info=info)
     UserInfo.create(info=info)
     db.session.commit()
     return (True, info['user_id'])
Example #9
0
    def wrapper(*args, **kwargs):
        if 'Authorization' in request.headers:
            tok = request.headers.get('Authorization')[7:]
        else:
            return INVALID_ACCESS_TOKEN()

        uid, expires = Token.load_access_token(g.rds, tok)
        uid = int(uid) if uid else 0
        expires = int(expires) if expires else 0
        if not uid:
            return INVALID_ACCESS_TOKEN()
        if time.time() > expires:
            logging.debug("access token expire")
            return EXPIRE_ACCESS_TOKEN()
        request.uid = uid
        return f(*args, **kwargs)
Example #10
0
    def decorated(*args, **kwargs):        
        auth = web.ctx.env['HTTP_AUTHORIZATION'] if 'HTTP_AUTHORIZATION' in  web.ctx.env else None
        unauth = True
        uid = 0
        if len(auth) > 7 and auth[:7] == "Bearer ":
            tok = auth[7:]
            uid, expires = Token.load_access_token(rds, tok)
            uid = int(uid) if uid else 0
            expires = int(expires) if expires else 0
            if uid and time.time() < expires:
                unauth = False

        if unauth :
            web.ctx.status = '401 Unauthorized'
            return Unauthorized()

        web.ctx.uid = uid
        return f(*args, **kwargs)
Example #11
0
    def post(self):
        data = request.get_json()

        user = User.query.filter_by(email=data['email']).first()

        if user is None or\
           not check_password_hash(user.password, data['password']):
            raise Unauthorized

        current_time = datetime.datetime.utcnow()
        expiration_date = current_time + datetime.timedelta(weeks=6)

        token = Token(user, binascii.hexlify(os.urandom(127)), expiration_date)

        db.session.add(token)
        db.session.commit()

        return token
Example #12
0
    def lexer_analysis(cls, stream):
        Lexer.bufferStream = stream
        token_list = []
        try:
            Lexer.read_char()
            while Lexer.currentStr != '':
                # 消除特殊符号
                if Lexer.currentStr in ['\n', '\t', '\f', '\r', ' ']:
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '+':
                    token_list.append(Token(Token.PLUS, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '-':
                    token_list.append(Token(Token.MINUS, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '*':
                    token_list.append(Token(Token.MUL, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '%':
                    token_list.append(Token(Token.MODE, Lexer.lineNum))
                    Lexer.read_char()
                    continue

                elif Lexer.currentStr == '(':
                    token_list.append(Token(Token.LPARENT, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == ')':
                    token_list.append(Token(Token.RPARENT, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '[':
                    token_list.append(Token(Token.LBRACKET, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == ']':
                    token_list.append(Token(Token.RBRACKET, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '{':
                    token_list.append(Token(Token.LBRACE, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '}':
                    token_list.append(Token(Token.RBRACE, Lexer.lineNum))
                    Lexer.read_char()
                    continue

                elif Lexer.currentStr == ',':
                    token_list.append(Token(Token.COMMA, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == ';':
                    token_list.append(Token(Token.SEMI, Lexer.lineNum))
                    Lexer.read_char()
                    continue

                elif Lexer.currentStr == '/':
                    Lexer.read_char()
                    if Lexer.currentStr == '*':
                        token_list.append(Token(Token.LCOM, Lexer.lineNum))
                        Lexer.read_char()
                        while Lexer.currentStr != '':
                            if Lexer.currentStr == '*':
                                Lexer.read_char()
                                if Lexer.currentStr == '/':
                                    token_list.append(Token(Token.RCOM, Lexer.lineNum))
                                    Lexer.read_char()
                                    break
                            Lexer.read_char()
                        continue
                    elif Lexer.currentStr == '/':
                        while Lexer.currentStr != '\n':
                            Lexer.read_char()
                        token_list.append(Token(Token.SCOM, Lexer.lineNum))
                        continue
                    token_list.append(Token(Token.DIV, Lexer.lineNum))
                    continue

                elif Lexer.currentStr == '=':
                    Lexer.read_char()
                    if Lexer.currentStr == '=':
                        token_list.append(Token(Token.EQ, Lexer.lineNum))
                        Lexer.read_char()
                        continue
                    token_list.append(Token(Token.ASSIGN, Lexer.lineNum))
                    continue

                elif Lexer.currentStr == '<':
                    Lexer.read_char()
                    if Lexer.currentStr == '=':
                        token_list.append(Token(Token.LET, Lexer.lineNum))
                        continue
                    token_list.append(Token(Token.LT, Lexer.lineNum))
                    continue

                elif Lexer.currentStr == '>':
                    Lexer.read_char()
                    if Lexer.currentStr == '=':
                        token_list.append(Token(Token.GET, Lexer.lineNum))
                        continue
                    token_list.append(Token(Token.GT, Lexer.lineNum))
                    continue

                elif Lexer.currentStr == '!':
                    Lexer.read_char()
                    if Lexer.currentStr == '=':
                        token_list.append(Token(Token.NEQ, Lexer.lineNum))
                        continue

                elif 'a' <= Lexer.currentStr <= 'z' or 'A' <= Lexer.currentStr <= 'Z':
                    string_temp = Lexer.currentStr
                    Lexer.read_char()
                    while ('a' <= Lexer.currentStr <= 'z') or ('A' <= Lexer.currentStr <= 'Z') or \
                            ('0' <= Lexer.currentStr <= '9') or (Lexer.currentStr == '_'):
                        string_temp += Lexer.currentStr
                        Lexer.read_char()
                    token = Token(line_num=Lexer.lineNum)
                    if string_temp == 'int':
                        token.set_type(Token.INT)
                    elif string_temp == 'double':
                        token.set_type(Token.DOUBLE)
                    elif string_temp == 'if':
                        token.set_type(Token.IF)
                    elif string_temp == 'else':
                        token.set_type(Token.ELSE)
                    elif string_temp == 'while':
                        token.set_type(Token.WHILE)
                    elif string_temp == 'read':
                        token.set_type(Token.READ)
                    elif string_temp == 'write':
                        token.set_type(Token.WRITE)
                    elif string_temp == 'break':
                        token.set_type(Token.BREAK)
                    elif string_temp in ['True', 'False']:
                        token.set_type(Token.BOOL)
                        value = True if string_temp == 'True' else False
                        token.set_value(value)
                    else:
                        token.set_type(Token.ID)
                        token.set_value(string_temp)
                    token_list.append(token)
                    continue

                elif '0' <= Lexer.currentStr <= '9':
                    is_double = False
                    int_temp = Lexer.currentStr
                    Lexer.read_char()
                    while '0' <= Lexer.currentStr <= '9' or Lexer.currentStr == '.':
                        if Lexer.currentStr == '.':
                            is_double = True
                        int_temp += Lexer.currentStr
                        Lexer.read_char()
                    if is_double:
                        token_list.append(Token(Token.LITERAL_DOU, Lexer.lineNum, string.atof(int_temp)))
                        continue
                    token_list.append(Token(Token.LITERAL_INT, Lexer.lineNum, string.atoi(int_temp)))
                    continue
            cls.bufferStream = None
            cls.currentStr = ""
            cls.lineNum = 1
            return token_list

        except Exception as e:
            print e
Example #13
0
 def __init__(self, line_num, t_type):
     Exception.__init__(self)
     self.content = 'line .' + str(line_num) + ':next token should be ' + Token(t_type).to_string()
Example #14
0
    def lexer_analysis(cls, stream):
        Lexer.bufferStream = stream
        token_list = []
        try:
            Lexer.read_char()
            while Lexer.currentStr != '':
                # 消除特殊符号
                if Lexer.currentStr in ['\n', '\t', '\f', '\r', ' ']:
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '+':
                    token_list.append(Token(Token.PLUS, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '-':
                    token_list.append(Token(Token.MINUS, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '*':
                    token_list.append(Token(Token.MUL, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '%':
                    token_list.append(Token(Token.MODE, Lexer.lineNum))
                    Lexer.read_char()
                    continue

                elif Lexer.currentStr == '(':
                    token_list.append(Token(Token.LPARENT, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == ')':
                    token_list.append(Token(Token.RPARENT, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '[':
                    token_list.append(Token(Token.LBRACKET, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == ']':
                    token_list.append(Token(Token.RBRACKET, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '{':
                    token_list.append(Token(Token.LBRACE, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == '}':
                    token_list.append(Token(Token.RBRACE, Lexer.lineNum))
                    Lexer.read_char()
                    continue

                elif Lexer.currentStr == ',':
                    token_list.append(Token(Token.COMMA, Lexer.lineNum))
                    Lexer.read_char()
                    continue
                elif Lexer.currentStr == ';':
                    token_list.append(Token(Token.SEMI, Lexer.lineNum))
                    Lexer.read_char()
                    continue

                elif Lexer.currentStr == '/':
                    Lexer.read_char()
                    if Lexer.currentStr == '*':
                        token_list.append(Token(Token.LCOM, Lexer.lineNum))
                        Lexer.read_char()
                        while Lexer.currentStr != '':
                            if Lexer.currentStr == '*':
                                Lexer.read_char()
                                if Lexer.currentStr == '/':
                                    token_list.append(
                                        Token(Token.RCOM, Lexer.lineNum))
                                    Lexer.read_char()
                                    break
                            Lexer.read_char()
                        continue
                    elif Lexer.currentStr == '/':
                        while Lexer.currentStr != '\n':
                            Lexer.read_char()
                        token_list.append(Token(Token.SCOM, Lexer.lineNum))
                        continue
                    token_list.append(Token(Token.DIV, Lexer.lineNum))
                    continue

                elif Lexer.currentStr == '=':
                    Lexer.read_char()
                    if Lexer.currentStr == '=':
                        token_list.append(Token(Token.EQ, Lexer.lineNum))
                        Lexer.read_char()
                        continue
                    token_list.append(Token(Token.ASSIGN, Lexer.lineNum))
                    continue

                elif Lexer.currentStr == '<':
                    Lexer.read_char()
                    if Lexer.currentStr == '=':
                        token_list.append(Token(Token.LET, Lexer.lineNum))
                        continue
                    token_list.append(Token(Token.LT, Lexer.lineNum))
                    continue

                elif Lexer.currentStr == '>':
                    Lexer.read_char()
                    if Lexer.currentStr == '=':
                        token_list.append(Token(Token.GET, Lexer.lineNum))
                        continue
                    token_list.append(Token(Token.GT, Lexer.lineNum))
                    continue

                elif Lexer.currentStr == '!':
                    Lexer.read_char()
                    if Lexer.currentStr == '=':
                        token_list.append(Token(Token.NEQ, Lexer.lineNum))
                        continue

                elif 'a' <= Lexer.currentStr <= 'z' or 'A' <= Lexer.currentStr <= 'Z':
                    string_temp = Lexer.currentStr
                    Lexer.read_char()
                    while ('a' <= Lexer.currentStr <= 'z') or ('A' <= Lexer.currentStr <= 'Z') or \
                            ('0' <= Lexer.currentStr <= '9') or (Lexer.currentStr == '_'):
                        string_temp += Lexer.currentStr
                        Lexer.read_char()
                    token = Token(line_num=Lexer.lineNum)
                    if string_temp == 'int':
                        token.set_type(Token.INT)
                    elif string_temp == 'double':
                        token.set_type(Token.DOUBLE)
                    elif string_temp == 'if':
                        token.set_type(Token.IF)
                    elif string_temp == 'else':
                        token.set_type(Token.ELSE)
                    elif string_temp == 'while':
                        token.set_type(Token.WHILE)
                    elif string_temp == 'read':
                        token.set_type(Token.READ)
                    elif string_temp == 'write':
                        token.set_type(Token.WRITE)
                    elif string_temp == 'break':
                        token.set_type(Token.BREAK)
                    elif string_temp in ['True', 'False']:
                        token.set_type(Token.BOOL)
                        value = True if string_temp == 'True' else False
                        token.set_value(value)
                    else:
                        token.set_type(Token.ID)
                        token.set_value(string_temp)
                    token_list.append(token)
                    continue

                elif '0' <= Lexer.currentStr <= '9':
                    is_double = False
                    int_temp = Lexer.currentStr
                    Lexer.read_char()
                    while '0' <= Lexer.currentStr <= '9' or Lexer.currentStr == '.':
                        if Lexer.currentStr == '.':
                            is_double = True
                        int_temp += Lexer.currentStr
                        Lexer.read_char()
                    if is_double:
                        token_list.append(
                            Token(Token.LITERAL_DOU, Lexer.lineNum,
                                  string.atof(int_temp)))
                        continue
                    token_list.append(
                        Token(Token.LITERAL_INT, Lexer.lineNum,
                              string.atoi(int_temp)))
                    continue
            cls.bufferStream = None
            cls.currentStr = ""
            cls.lineNum = 1
            return token_list

        except Exception as e:
            print e
Example #15
0
def add_token(title):
    session = db.Session()
    token = Token(title=title)
    session.add(token)
    session.commit()
    return token.format()