# Path: config/setting.py

# 
# Path: util/login.py
# def login(userid):
#     # 1. sha1(salt+ip+userid+now)
#     now=str(datetime.now())
#     userid=str(userid)
#     hash=sha1(salt+userid+now)
#     # 2. 储存hash id,userid,hash
#     db.insert("login",userid=userid,hash=hash,time=now,discard=0)
#     # 3. write cookie ua:sha1
#     web.setcookie('cu', hash, 3600*24*30)
#     return hash


from config import setting
from util import login
def update_oauth_userid(name,id,oauth_id):
    data = {}
    data[name+"_id"] = oauth_id
    db.update("user",where="id=$id",vars={"id":id},**data)

def update_access_token(name,id,token):
    data = {}
    data[name+"_access_token"] = token
    db.update("user",where=name+"_id=$id",vars={"id":id},**data)

def exist_oauth_user(name,info):
    data = parse_data(name,info)
    if not check(name,data):
        return False

    rows = db.select("user",where=name+"_id=$id",vars={"id":data[name+"_id"]})
    if rows:
        return rows[0]
    else:
        return False

def login_oauth_user(name,info):
    data = parse_data(name,info)
    if not check(name,data):
        raise Exception("login arguments error")

    users = db.select("user",where=name+"_id="+data[name+"_id"])
    if not users:
        raise Exception("user not found")


# Path: config/setting.py

# 
# Path: util/login.py
# def login(userid):
#     # 1. sha1(salt+ip+userid+now)
#     now=str(datetime.now())
#     userid=str(userid)
#     hash=sha1(salt+userid+now)
#     # 2. 储存hash id,userid,hash
#     db.insert("login",userid=userid,hash=hash,time=now,discard=0)
#     # 3. write cookie ua:sha1
#     web.setcookie('cu', hash, 3600*24*30)
#     return hash


# Path: model/user.py
from config import setting
from util import login

def update_oauth_userid(name,id,oauth_id):
    data = {}
    data[name+"_id"] = oauth_id
    db.update("user",where="id=$id",vars={"id":id},**data)

def update_access_token(name,id,token):
    data = {}
    data[name+"_access_token"] = token
    db.update("user",where=name+"_id=$id",vars={"id":id},**data)

def exist_oauth_user(name,info):
    data = parse_data(name,info)
    if not check(name,data):
        return False

    rows = db.select("user",where=name+"_id=$id",vars={"id":data[name+"_id"]})
    if rows:
        return rows[0]
    else:
        return False

def login_oauth_user(name,info):
    data = parse_data(name,info)
    if not check(name,data):
        raise Exception("login arguments error")

    users = db.select("user",where=name+"_id="+data[name+"_id"])
    if not users:
        raise Exception("user not found")


    return login.login(users[0]["id"])