AuthenticateController.cs 10.2 KB
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using log4net;
using AIAHTML5.API.Constants;
using AIAHTML5.API.Models;
using System.Collections;

namespace AIAHTML5.API.Controllers
{
    public class AuthenticateController : ApiController
    {
        // GET api/authenticate
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/authenticate/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/authenticate
        public HttpResponseMessage Post([FromBody]JObject credentials)
        {
            ILog logger = log4net.LogManager.GetLogger((System.Reflection.MethodBase.GetCurrentMethod().DeclaringType));
            logger.Debug("inside POST");

            dynamic authenticationRepsonse;
          
            //01. check user is authenticated or not by login credential macth
            bool isUserAuthenticated = AIAHTML5.API.Models.Users.IsUserAuthenticated(credentials);

            User userInfo = new Models.User();

            //02. Get User details
            userInfo = AIAHTML5.API.Models.Users.getUserDetails(credentials);

            if(isUserAuthenticated)
            {
                //04.insert Log login details
                AIAHTML5.API.Models.Users.insertLoginDetails(userInfo.Id);

                //03.delete past wrong login attempts of user
                userInfo.IsCorrectLoginId = true;
                userInfo.IsCorrectPassword = true;

                int wrongAttemptDeteledCount =  AIAHTML5.API.Models.Users.deletePastWrongAttempts(userInfo.Id);
                if (wrongAttemptDeteledCount < 0)
                {
                    logger.Fatal("Unable to delete past wrong login attempts for userId= "+userInfo.Id);
                }

                // for ADMIN (superadmin/ general admin) users by default all module loads
                if (userInfo.UserType == AIAHTML5.API.Models.User.SUPER_ADMIN || userInfo.UserType == AIAHTML5.API.Models.User.GENERAL_ADMIN)
                {
                    userInfo.Modules = AIAHTML5.API.Models.Users.getAllModulesList();
                    
                }
                else
                {
                    //03. get the license id for aUTHENTICATED USER    
                    userInfo.LicenseId = AIAHTML5.API.Models.Users.getLicenseIdForThisUser(userInfo.Id, "license");
                    userInfo.EditionId = AIAHTML5.API.Models.Users.getLicenseIdForThisUser(userInfo.Id, "edition");
                                       
                    //05.Check user is active or not
                    // Below statement required as tl says it is required for better code readability
                    userInfo.IsActive = userInfo.IsActive;

                    
                        //5.1 get license/ licenseSubscription details
                        //objUser.License.IsActive = AIAHTML5.API.Models.Users.isLicenseActive(objUser.LicenseId);
                        userInfo.License = AIAHTML5.API.Models.Users.getLicenseDetails(userInfo.LicenseId);
                        userInfo.LicenseSubscriptions = AIAHTML5.API.Models.Users.getLicenseSubscriptionDetails(userInfo.LicenseId);

                        //5.2 check the License expiration irespective of either user is active or not because on AIA
                        //we shows the License expiration message for inactive users too
                        bool isLicenseSubscriptionExpired = false;
                        string expirationDate = AIAHTML5.API.Models.Users.getLicenseExpirationDate(userInfo.LicenseId,out isLicenseSubscriptionExpired);

                        // send message to the UI for license expiration
                        //5.2 Check for subscription Expiration [Promoted for case if license inactive along with subscription expired]
                        if (isLicenseSubscriptionExpired)
                        {
                            userInfo.IsSubscriptionExpired = isLicenseSubscriptionExpired;
                            userInfo.SubscriptionExpirationDate = expirationDate;
                        }
                       
                            if (userInfo.License.IsActive)
                            {                               
                                //Insert user login details
                                //AIAHTML5.API.Models.Users.insertLoginDetails(objUser.Id);

                                if (!userInfo.License.IsTermAccepted)
                                {
                                    ArrayList termsList = AIAHTML5.API.Models.Users.getTermsOfServiceText();
                                    foreach (Hashtable item in termsList)
                                    {
                                        userInfo.TermsOfServiceTitle = item["title"].ToString();
                                        userInfo.TermsOfServiceText = item["content"].ToString();
                                    }
                                }
                                else
                                {
                                    userInfo.Modules = AIAHTML5.API.Models.Users.getModuleListByLicenseId(userInfo.LicenseId);
                                }
                            }
                        
                        //else
                        //{
                        //    //6.


                        //    // now return this list to the UI
                        //}
                    //}
                    //else
                    //{
                    //    // send message back to th UI that user is inactive
                    //}
                }

            }
            else
            {
                bool isCorrectLoginId = AIAHTML5.API.Models.Users.isCredentialCorrect(credentials, userInfo, "loginId");

                if (!isCorrectLoginId)
                {
                    // send message back to th UI that login id is incorrect
                    userInfo.IsCorrectLoginId = isCorrectLoginId;
                }
                else
                {
                    userInfo.IsCorrectLoginId = true;
                    bool isCorrectPassword = AIAHTML5.API.Models.Users.isCredentialCorrect(credentials, userInfo, "password");

                    if (!isCorrectPassword)
                    {
                        // send message back to th UI that password is incorrect
                        userInfo.IsCorrectPassword = false;

                        //get wrong attempt count of user
                        userInfo.IncorrectLoginAttemptCount = AIAHTML5.API.Models.Users.checkNoOfWrongAttempts(userInfo.Id) + 1;
                        userInfo.LoginFailureCauseId = ErrorHelper.E_PASSWORD_NOT_MATCH;

                        //01. insert wrong attempt in dtabase
                        int updateCount = AIAHTML5.API.Models.Users.saveWrongAttemptofUser(userInfo.Id);

                        if (updateCount < 0)
                        {
                            //Put the log in log file
                            logger.Fatal("Unable to Update past wrong login attempts for userId= " + userInfo.Id);
                        }
                        else
                        {

                            //02. check no of wrong attempts
                            //userInfo.IncorrectLoginAttemptCount = AIAHTML5.API.Models.Users.checkNoOfWrongAttempts(userInfo.Id);
                            //if (userInfo.IncorrectLoginAttemptCount >= 5)
                            //{
                            //    userInfo.IsBlocked = true;
                            //    // send block message
                            //}
                            //else
                            //{
                            //    // send message back to UI for login fail
                            //}

                            if (userInfo.IncorrectLoginAttemptCount > 4)
                            {
                                userInfo.IsBlocked = true;
                                userInfo.LoginFailureCauseId = ErrorHelper.E_USER_ID_BLOCKED_24_HRS;
                            }
                        }
                    }
                    // unreachable code detected as license is null
                    //if (userInfo.License != null && !string.IsNullOrEmpty(userInfo.License.AccountNumber))
                    //{
                    //    int result = AIAHTML5.API.Models.Users.insertUserLoginLog(userInfo.License.AccountNumber, userInfo.LoginFailureCauseId, null, userInfo.EditionId.ToString(), null);
                    //    if (result < 0)
                    //        logger.Fatal("Unable to insert wrong attempt detail in UserLoginLog table for accountNumber= " + userInfo.License.AccountNumber);
                    //}
                }
            }

            if(userInfo.IsCorrectLoginId)
                authenticationRepsonse = JsonConvert.SerializeObject(userInfo); 
            else
                authenticationRepsonse = AIAConstants.USER_NOT_FOUND;

                //if (Convert.ToString(authenticationRepsonse) != AIAConstants.USER_NOT_FOUND && Convert.ToString(authenticationRepsonse) != AIAConstants.ERROR_IN_FECTHING_DETAILS && Convert.ToString(authenticationRepsonse)!= AIAConstants.SQL_CONNECTION_ERROR)
                //{
                //    //string userDetails = Newtonsoft.Json.JsonConvert.SerializeObject(authenticationRepsonse);
                //    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(authenticationRepsonse) };
                //}
                //else
                //{
                    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(authenticationRepsonse) };

                //}
            }
        

        // PUT api/authenticate/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/authenticate/5
        public void Delete(int id)
        {
        }
    }
}