0b96a07 by Anon Ray at 2014-06-03 1
# -*- coding utf-8 -*-
2
# User Management::User
3
4
from datetime import datetime
5
from flask import session
6
from flask import current_app
1e7645a by Anon Ray at 2014-06-03 7
8
from swtstore.classes.database import db
0b96a07 by Anon Ray at 2014-06-03 9
10
11
class User(db.Model):
12
    """ docstring """
13
14
    __tablename__ = 'users'
15
16
    id = db.Column(db.Integer, primary_key=True)
17
    username = db.Column(db.String(80))
18
    email = db.Column(db.String(120), unique=True)
19
    created = db.Column(db.DateTime, default=datetime.utcnow)
20
    last_active = db.Column(db.DateTime, default=datetime.utcnow)
21
22
    def __init__(self, username, email):
23
        self.username = username
24
        self.email = email
25
26
    def update(self, **kwargs):
27
        if kwargs.get('username'):
28
            self.username = kwargs.get('username')
29
        if kwargs.get('last_active'):
30
            current_app.logger.debug('Updated last_active timestamp %s for %s',
1e7645a by Anon Ray at 2014-06-03 31
                                     kwargs.get('last_active'), self)
0b96a07 by Anon Ray at 2014-06-03 32
            self.last_active = kwargs.get('last_active')
33
34
        self.persist()
35
36
    # persist current object in the database
37
    def persist(self):
38
        db.session.add(self)
39
        db.session.commit()
40
41
    # delete from database
42
    def remove(self):
43
        db.session.delete(self)
44
        db.session.commit()
45
46
    @staticmethod
47
    def getCurrentUser():
48
        if 'email' in session:
49
            user = User.query.filter_by(email=session['email']).first()
50
            user.update(last_active=datetime.utcnow())
51
            return user
52
        return None
53
54
    @staticmethod
55
    def getByName(username):
56
        return User.query.filter_by(username=username).first()
57
58
    def to_dict(self):
59
        return {
60
            'id': self.id,
61
            'username': self.username,
62
            'email': self.email,
48b7772 by Anon Ray at 2014-06-03 63
            #'created': self.created.isoformat(),
64
            'created': self.created.strftime('%a, %d %b %Y, %I:%M %p UTC'),
65
            #'last_active': self.last_active.isoformat()
66
            'last_active': self.last_active.strftime('%a, %d %b %Y, %I:%M %p UTC')
0b96a07 by Anon Ray at 2014-06-03 67
        }
68
69
    def __repr__(self):
70
        return '<User:: %r %r>' % (self.username, self.email)