AppUser.cs 6.81 KB
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace AIAHTML5.Server.Models
{
    [BsonIgnoreExtraElements]
    public class AppUser
    {
        public ObjectId _id { get; set; }
        public string name;
        public string emailAddress;
        public string mobileNumber;
        public string password;

        internal static dynamic GetRegisteredCustomers()
        {
            var client = new MongoClient();
            var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

            var usersCol = db.GetCollection<dynamic>("users");

            var customers = usersCol.Find(new BsonDocument()).ToList();

            return customers;
        }

        public string[] apps;

        [BsonIgnore]
        public bool successful;

        [BsonIgnore]
        public string message;

        internal static bool IsResetPasswordLinkExpired(string userId)
        {
            var client = new MongoClient();
            var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

            var col = db.GetCollection<BsonDocument>("users");

            var filter = Builders<BsonDocument>.Filter.Eq("_id", ObjectId.Parse(userId)) & Builders<BsonDocument>.Filter.Exists("resetPasswordLinkValidity");

            var user = col.Find(filter).SingleOrDefault();

            if (user == null)
                return true;
            else
            {
                DateTime expiryDateTime = user["resetPasswordLinkValidity"].ToUniversalTime();
                DateTime currentDateTime = DateTime.UtcNow;

                if (currentDateTime > expiryDateTime)
                    return true;
                else
                    return false;
            }
        }

        internal static void UpdatePassword(string userId, string password)
        {
            if (!IsResetPasswordLinkExpired(userId))
            {
                var client = new MongoClient();
                var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

                var col = db.GetCollection<dynamic>("users");

                var result = col.UpdateOne(Builders<dynamic>.Filter.Eq("_id", ObjectId.Parse(userId)),
                    Builders<dynamic>.Update
                        .Set("password", password)
                        .Set("lastPasswordChangeDate", DateTime.UtcNow)
                        .Unset("resetPasswordLinkValidity"));
            }
        }

        public static dynamic Authenticate(string applicationName, string username, string password)
        {
            try
            {
                var emailFilter = Builders<dynamic>.Filter.Eq("emailAddress", username) & Builders<dynamic>.Filter.Eq("password", password);
                var passwordFilter = Builders<dynamic>.Filter.Eq("mobileNumber", username) & Builders<dynamic>.Filter.Eq("password", password);

                var client = new MongoClient();
                var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

                var col = db.GetCollection<dynamic>("users");

                dynamic user = col.Find(emailFilter).SingleOrDefault();
                if (user == null)
                    user = col.Find(passwordFilter).SingleOrDefault();

                user.successful = true;

                return user;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public bool isRegistered()
        {
            return false;
        }

        public static bool isRegistered(string emailAddress, string mobileNumber)
        {
            
            FilterDefinition<AppUser>[] filters = { Builders<AppUser>.Filter.Eq("emailAddress", emailAddress), Builders<AppUser>.Filter.Eq("mobileNumber", mobileNumber) }; 

            var client = new MongoClient();
            var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

            var col = db.GetCollection<AppUser>("users");
            List<AppUser> list;
            
            list = col.Find(Builders<AppUser>.Filter.Or(filters)).ToList();

            if (list.Count > 0)
                return true;
            else
                return false;

        }

        public static bool isRegistered(string emailAddress)
        {
            var client = new MongoClient();
            var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

            var col = db.GetCollection<AppUser>("users");
            List<AppUser> list;

            list = col.Find(Builders<AppUser>.Filter.Eq("emailAddress", emailAddress)).ToList();

            if (list.Count > 0)
                return true;
            else
                return false;
        }

        public static dynamic GetUser(string userId)
        {
            var client = new MongoClient();
            var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

            var col = db.GetCollection<dynamic>("users");

            dynamic userDetails = col.Find(Builders<dynamic>.Filter.Eq("_id", ObjectId.Parse(userId))).SingleOrDefault();

            return userDetails;
            
        }

        public static AppUser Create(JObject userObject)
        {
            AppUser user = userObject.ToObject<AppUser>();

            if (isRegistered(user.emailAddress, user.mobileNumber))
            {
                throw new Exception("Our records indicate that you are already registered.");
            }
            else
            {
                var client = new MongoClient();
                var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

                var col = db.GetCollection<AppUser>("users");

                user.name = user.name.ToTitleCase();

                col.InsertOne(user);

                user.successful = true;

                user.message = "User created successfully.";

                return user;
            }
        }

        public static string SetPasswordResetExpiry(string username)
        {
            if (!isRegistered(username))
            {
                throw new Exception("This email address is not registered with us.");
            }

            var client = new MongoClient();
            var db = client.GetDatabase(ConfigurationManager.AppSettings["database"]);

            var col = db.GetCollection<dynamic>("users");

            var result = col.UpdateOne(Builders<dynamic>.Filter.Eq("emailAddress", username),
                Builders<dynamic>.Update.Set("resetPasswordLinkValidity", DateTime.UtcNow.AddDays(1).ToUniversalTime()));

            var user = col.Find(Builders<dynamic>.Filter.Eq("emailAddress", username)).SingleOrDefault();
            return user._id.ToString();

        }
    }
}