本文整理汇总了Python中models.User.generate_auth_token方法的典型用法代码示例。如果您正苦于以下问题:Python User.generate_auth_token方法的具体用法?Python User.generate_auth_token怎么用?Python User.generate_auth_token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.User
的用法示例。
在下文中一共展示了User.generate_auth_token方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def register():
if 'email' not in request.form:
return jsonify(errors=['Email is required']), 401
if 'password' not in request.form:
return jsonify(errors=['Password is required']), 401
token = User.generate_auth_token(request.form['email'], request.form['password'])
if token:
return jsonify(token=token), 200
user = User.objects(email=request.form['email'])
if user:
return jsonify(errors=['Email already taken']), 401
if not is_email_address_valid(request.form['email']):
return jsonify(errors=['Invalid email address']), 401
if not is_password_valid(request.form['password']):
return jsonify(errors=['Password too short']), 401
user = User(email=request.form['email'])
user.hash_password(request.form['password'])
if user.save():
token = User.generate_auth_token(request.form['email'], request.form['password'])
return jsonify(token=token), 200
return jsonify(errors=['Undefined error']), 401
示例2: complete
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def complete(request):
auth_code = request.GET.get('code')
try:
flow = client.flow_from_clientsecrets(
'restful_api/client_secret.json',
scope='',
redirect_uri='http://localhost:8000/restful_api/index'
)
except client.FlowExchangeError:
return HttpResponseForbidden('Failed to upgrade the authorization code.')
if auth_code is not None:
credentials = flow.step2_exchange(auth_code)
access_token = credentials.access_token
url = ('https://www.googleapis.com/plus/v1/people/me?access_token=%s' % access_token)
h = httplib2.Http()
data = h.request(url, 'GET')
profile_data = json.loads(data[1])
picture = profile_data.get('image').get('url')
email = profile_data.get('emails')[0].get('value')
user = User.objects.filter(email=email).first()
username = email.split('@')[0]
if not user:
user = User(username=username, picture=picture, email=email)
user.save()
token = user.generate_auth_token()
return JsonResponse(
{
'status': 'user created successfully!',
'token': token.decode('ascii'),
'object':
{
'username': user.username,
'picture': str(user.picture),
'email': user.email
}
}
)
else:
token = user.generate_auth_token()
return JsonResponse(
{
'status': 'user already exist with the associated email address!',
'token': token.decode('ascii')
}
)
示例3: setUp
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def setUp(self):
super(BaseFriendshipTest, self).setUp()
self.steve = {
'name' : 'steve jobs',
'email' : '[email protected]',
'picture' : 'steve_jobs.jpg',
'token' : User.generate_auth_token('[email protected]'),
'num_random': 0
}
self.bill = {
'name' : 'bill gates',
'email' : '[email protected]',
'picture' : 'bill_gates.jpg',
'token' : User.generate_auth_token('[email protected]'),
'num_random': 0
}
self.db.session.add_all([User(**self.steve), User(**self.bill)])
self.db.session.commit()
示例4: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def post(self):
user = User.query.filter_by(username=self.data['username']).first()
if user is not None:
return {'message': 'User already exists'}, 400
user = User(self.data['username'],
self.data['password'],
self.data['email'])
db.session.add(user)
db.session.commit()
return {'token': user.generate_auth_token()}
示例5: login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def login():
if 'email' not in request.form:
return jsonify(errors=['Email is required']), 401
if 'password' not in request.form:
return jsonify(errors=['Password is required']), 401
token = User.generate_auth_token(request.form['email'], request.form['password'])
if token:
return jsonify(token=token), 200
return jsonify(errors=['Invalid login']), 401
示例6: oauth_callback
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def oauth_callback(provider):
oauth = OAuthSignIn.get_provider(provider)
social_id, username, email, picture = oauth.callback()
user = session.query(User).filter_by(email=email).first()
if not user:
user = User(username = username, picture = picture, email = email)
session.add(user)
membership = OAuthMembership(provider = provider, provider_userid = social_id, user = user)
session.add(membership)
session.commit()
login_session['username'] = user.username
token = user.generate_auth_token(1600)
return redirect(url_for('index', token = token))
示例7: api_create_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def api_create_user():
""" Creates a new user, with sign up and login the user. """
username = request.json.get("username")
password = request.json.get("password")
realname = request.json.get("realname")
if username is None or password is None or realname is None:
abort(400) # missing arguments
if User.query.filter_by(username=username).first() is not None:
return make_response(jsonify({"error": "User with this username already exists"}), 400) # existing user
user = User(username, realname, password, False)
user.add(user)
flask_login.login_user(user)
token = user.generate_auth_token()
session["token"] = token
return jsonify({"token": token.decode("ascii")})
示例8: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def post(self):
args = parser.parse_args()
print(args)
user = User(
email=args['email'],
password=args['password']
)
try:
db.session.add(user)
db.session.commit()
status = 'success'
token = user.generate_auth_token()
db.session.close()
return jsonify({'id': user.id, 'email': user.email, 'token': token})
except:
status = False
return jsonify(status)
示例9: new_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def new_user():
if not request.json or not 'username' in request.json or not 'password' in request.json:
print "missing arguments"
abort(400)
username = request.json.get('username')
password = request.json.get('password')
if not username or not password:
abort(400)
if session.query(User).filter_by(username = username).first() is not None:
print "existing user"
user = session.query(User).filter_by(username=username).first()
return jsonify({'message':'user already exists'}), 409#, {'Location': url_for('get_user', id = user.id, _external = True)}
user = User(username = username)
user.hash_password(password)
session.add(user)
session.commit()
token = user.generate_auth_token()
return jsonify({'token': token.decode('ascii')})
示例10: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def post(self):
result = dict()
args = self.parser.parse_args()
if session.get('captcha') == args['captcha']:
result['captchaNotRight'] = False
user = User.query.filter_by(email=args['email']).first()
if user:
result['isSucceed'] = False
result['emailExist'] = True
else:
user = User(args['email'], args['password'])
db.session.add(user)
db.session.commit()
result['isSucceed'] = True
result['loginEmail'] = user.email
result['token'] = user.generate_auth_token()
else:
result['isSucceed'] = False
result['captchaNotRight'] = True
return result, 201
示例11: setUp
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def setUp(self):
super(BaseGameTest, self).setUp()
self.users = {
'steve': {
'name' : 'steve jobs',
'email' : '[email protected]',
'picture': 'steve_jobs.jpg'
},
'bill': {
'name' : 'bill gates',
'email' : '[email protected]',
'picture': 'bill_gates.jpg'
},
'mark': {
'name' : 'mark zuckerberg',
'email' : '[email protected]',
'picture': 'mark_zuckerberg.jpg'
},
'paul': {
'name' : 'paul graham',
'email' : '[email protected]',
'picture': 'pg.jpg'
},
'obama': {
'name' : 'barack obama',
'email' : '[email protected]',
'picture': 'obama.jpg'
}
}
for name, user in self.users.items():
self.users[name]['token'] = User.generate_auth_token(self.users[name]['email'])
self.users[name]['num_random'] = 0
self.db.session.add_all([User(**user) for name, user in self.users.items()])
self.db.session.commit()
示例12: login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def login(provider):
#STEP 1 - Parse the auth code
auth_code = request.json.get('auth_code')
print "Step 1 - Complete, received auth code %s" % auth_code
if provider == 'google':
#STEP 2 - Exchange for a token
try:
# Upgrade the authorization code into a credentials object
oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
oauth_flow.redirect_uri = 'postmessage'
credentials = oauth_flow.step2_exchange(auth_code)
except FlowExchangeError:
response = make_response(json.dumps('Failed to upgrade the authorization code.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Check that the access token is valid.
access_token = credentials.access_token
url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
# If there was an error in the access token info, abort.
if result.get('error') is not None:
response = make_response(json.dumps(result.get('error')), 500)
response.headers['Content-Type'] = 'application/json'
# # Verify that the access token is used for the intended user.
# gplus_id = credentials.id_token['sub']
# if result['user_id'] != gplus_id:
# response = make_response(json.dumps("Token's user ID doesn't match given user ID."), 401)
# response.headers['Content-Type'] = 'application/json'
# return response
# # Verify that the access token is valid for this app.
# if result['issued_to'] != CLIENT_ID:
# response = make_response(json.dumps("Token's client ID does not match app's."), 401)
# response.headers['Content-Type'] = 'application/json'
# return response
# stored_credentials = login_session.get('credentials')
# stored_gplus_id = login_session.get('gplus_id')
# if stored_credentials is not None and gplus_id == stored_gplus_id:
# response = make_response(json.dumps('Current user is already connected.'), 200)
# response.headers['Content-Type'] = 'application/json'
# return response
print "Step 2 Complete! Access Token : %s " % credentials.access_token
#STEP 3 - Find User or make a new one
#Get user info
h = httplib2.Http()
userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
params = {'access_token': credentials.access_token, 'alt':'json'}
answer = requests.get(userinfo_url, params=params)
data = answer.json()
name = data['name']
picture = data['picture']
email = data['email']
#see if user exists, if it doesn't make a new one
user = session.query(User).filter_by(email=email).first()
if not user:
user = User(username = name, picture = picture, email = email)
session.add(user)
session.commit()
#STEP 4 - Make token
token = user.generate_auth_token(600)
#STEP 5 - Send back token to the client
return jsonify({'token': token.decode('ascii')})
#return jsonify({'token': token.decode('ascii'), 'duration': 600})
else:
return 'Unrecoginized Provider'
示例13: login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import generate_auth_token [as 别名]
def login(provider):
if provider == 'google':
code = request.json.get('auth_code')
try:
oauth_flow = flow_from_clientsecrets('client_secrets.json',
scope='')
oauth_flow.redirect_uri = 'postmessage'
credentials = oauth_flow.step2_exchange(code)
except FlowExchangeError:
response = make_response(json.dumps(
'Failed to upgrade the authorization code.', 401))
response.headers['Content-Type'] = 'application/json'
return response
# Check if the access token is valid
access_token = credentials.access_token
print 'In gconnect access token is %s' % access_token
url = ('https://www.googleapis.com/oauth2/v2/tokeninfo?access_token=%s'
% access_token)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
# If there was an error in the access token info, abort.
if result.get('error') is not None:
response = make_response(json.dumps(result.get('error')), 501)
response.headers['Content-Type'] = 'application/json'
return response
# Verify if that access token is used for the intended user.
gplus_id = credentials.id_token['sub']
if result['user_id'] != gplus_id:
response = make_response(
json.dumps("Token's user ID doesn't match given user ID."),
401)
response.headers['Content-Type'] = 'application/json'
return response
# Verify that the access token is valid for this app.
if result['issued_to'] != CLIENT_ID:
response = make_response(
json.dumps("Token's client ID doesn't match app's."), 401)
print "Token's client ID doesn't match app's."
response.headers['Content-Type'] = 'application/json'
return response
# Check if user is already logged in
stored_access_token = login_session.get('access_token')
stored_gplus_id = login_session.get('gplus_id')
if stored_access_token is not None and gplus_id == stored_gplus_id:
response = make_response(
json.dumps('Current user is already connected.'), 200)
print "Current user already connected."
print "Stored acces token now is %s" % stored_access_token
response.headers['Content-Type'] = 'application/json'
return response
# Store the access token in the session for later use.
login_session['access_token'] = credentials.access_token
login_session['gplus_id'] = gplus_id
login_session['provider'] = 'google'
print "Stored acces finally is %s" % login_session.get('access_token')
# Get user info
userinfo_url = "https://www.googleapis.com/oauth2/v2/userinfo"
params = {'access_token': credentials.access_token, 'alt': 'json'}
answer = requests.get(userinfo_url, params=params)
data = json.loads(answer.text)
login_session['username'] = data['name']
login_session['picture'] = data['picture']
login_session['email'] = data['email']
login_session['provider'] = 'google'
userId = login_session.get('user_id')
if not userId:
try:
user = session.query(User).filter_by(
email=login_session.get('email')).first()
userId = user.id
except:
userId = None
if userId is None:
user = User(username=login_session['username'],
email=login_session['email'],
picture=login_session['picture'])
session.add(user)
session.commit()
userId = user.id
user = session.query(User).filter_by(id=userId).one()
login_session['user_id'] = userId
name = user.username
print 'Hello %s, welcome to Pale Kale Salads & Smothies' % name
# Make the token
token = user.generate_auth_token(60)
# Send back the token to the client
return jsonify({'token': token.decode('ascii')})
else:
return 'Unrecognized Provider'