coding utf-8 import logging import datetime from flask ext login impor

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
import logging
import datetime
from flask.ext.login import UserMixin
from mongoengine import Document
from mongoengine.fields import (StringField, DateTimeField, BooleanField)
from werkzeug.security import generate_password_hash, check_password_hash
logger = logging.getLogger(__name__)
class Admin(Document, UserMixin):
meta = {
'collection': 'admins',
'indexes': ['-created_at', 'email', 'is_admin'],
'ordering': ['-created_at']
}
login = StringField(max_length=30)
password = StringField(max_length=90)
active = BooleanField(default=True)
created_at = DateTimeField(datetime.datetime.now)
@staticmethod
def _generate_password_hash(password):
return generate_password_hash(password, method='sha1', salt_length=8)
def _check_password_hash(self, password):
logger.debug("Hash: %s | Password: %s" % (self.password, password))
logger.debug("check_password_hash: %s" % check_password_hash(self.password, password))
return check_password_hash(self.password, password)
def save(self, *args, **kwargs):
if not self.created_at:
self.created_at = datetime.datetime.now()
return super(Admin, self).save(*args, **kwargs)
def set_password(self, password):
self.password = self._generate_password_hash(password)
@staticmethod
def authenticate(login, password=None):
user = Admin.objects(name=login).first()
if user is not None:
if password is not None:
if user._check_password_hash(password):
return user
return None
def get_id(self):
return unicode(self.id)
def is_active(self):
return self.active
def is_anonimous(self):
return False
def is_authenticated(self):
return True
def __str__(self):
return "<User: '%s'>" % (self.login)