Files
fb/app/models/user.py
2018-05-08 23:33:13 +05:30

113 lines
3.4 KiB
Python

from pymongo import MongoClient
import re
from bson import ObjectId
import json
class User:
def __init__(self, name, email, username, password):
self.name = name
self.email = email
self.username = username
self.password = password
class MongoUser:
def __init__(self):
config = json.load(open('./config.json', 'r'))
client = MongoClient(config['mongo_host'], config['mongo_port'])
self.db = client[config['db_name']]
def save(self, user):
self.db.users.insert_one(user)
def search_by_name(self, name):
result_cursor = self.db.users.find({'name': name})
matches = []
for user in result_cursor:
matches.append(user)
return matches
def delete_by_id(self, _id):
self.db.users.delete_one({'_id': ObjectId(_id)})
def update_by_id(self, _id, user):
self.db.users.update_one({'_id': ObjectId(_id)}, {'$set': user})
def authenticate(self, user):
result_cursor = self.db.users.find({'username': user.username, 'password':user.password})
if result_cursor.count() == 0:
return False
else:
return True
def list_all_users(self):
return self.db.users.find()
def add_stuff(self):
for i in range(10):
user = dict()
user['name'] = "name" + str(i)
user['email'] = "email" + str(i)
user['username'] = "username" + str(i)
user['password'] = "password" + str(i)
self.db.users.insert_one(user)
def find_user_name_by_credentials(self, user):
a = 3 if True else 1
result_cursor = self.db.users.find({'username': user.username})
matches = []
for user in result_cursor:
matches.append(user)
return matches[0]['name'] if len(matches) > 0 else None
def check_if_user_exists(self, username):
result_cursor = self.db.users.find({'username': username})
matches = []
for user in result_cursor:
matches.append(user)
if len(matches) > 0:
return True
else:
return False
def add_to_cart(self, user_id, product_id):
condition = {'_id': ObjectId(user_id)}
cursor = self.db.users.find(condition)
user_data = cursor[0] if cursor.count() > 0 else None
if user_data is None:
return False
if 'cart' not in user_data:
user_data['cart'] = []
if ObjectId(product_id) not in user_data['cart']:
user_data['cart'].append(ObjectId(product_id))
self.db.users.update_one(filter=condition, update={'$set':user_data})
return True
def get_by_id(self, _id):
query = {
'_id': ObjectId(_id)
}
cursor = self.db.users.find(query)
user = cursor[0] if cursor.count() > 0 else None
return user
def get_id_by_username(self, username):
cursor = self.db.users.find({'username': username})
user_data = cursor[0] if cursor.count() > 0 else None
if user_data is None:
return "Anonymous"
else:
matches = []
for user in cursor:
matches.append(user)
return matches[0]['_id']
def get_usercart_by_userid(self, user_id):
user = self.get_by_id(user_id)
return user['cart']