AccountController.cs 4.28 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using AIAHTML5.WebAPI.Models;
using AIAHTML5.WebAPI.ViewModels;
using JWT;
using System.Web.Http.Cors;
using Newtonsoft.Json.Linq;
using System.Web.Script.Serialization;
using AIAHTML5.WebAPI.Util;

namespace AIAHTML5.WebAPI.Controllers
{
     [EnableCors(origins: "http://localhost/AIA/API/", headers: "accept,content-type,origin,x-my-header", methods: "*")]
    public class AccountController : ApiController
    {
        
        [AllowAnonymous]
        //[Route("signin")]
        [HttpPost]

         public string Login(string userName, string password)
        {
            logging obj = new logging();
            obj.logData("called api");

          
            var loginSuccess = false;
            User userObj = new User();
            userObj.userName = "amrita.vishnoi@ebix.com";
            userObj.password = "education";
            userObj.Id = 1;         
           
                if (userName == userObj.userName && password ==userObj.password)
                {
                    loginSuccess = true;
                }
                else
                {
                    loginSuccess = false;
                }

                    if (loginSuccess)
                    {
                        object dbUser;
                        string token = CreateToken(userObj, out dbUser);

                        return token;

                     
                    }
                
            
            else
            {
                string msg = "token is not created";
                return msg;
                //var jsonString = Json(new JavaScriptSerializer().Serialize(new { msg }));
                //return JObject.Parse(jsonString.Content);   
            }
            //return response;
        }


        /// <summary>
        /// Create a Jwt with user information
        /// </summary>
        /// <param name="user"></param>
        /// <param name="dbUser"></param>
        /// <returns></returns>
        private static string CreateToken(User user, out object dbUser)
        {
            var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var expiry = Math.Round((DateTime.UtcNow.AddHours(2) - unixEpoch).TotalSeconds);
            var issuedAt = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds);
            var notBefore = Math.Round((DateTime.UtcNow.AddMonths(6) - unixEpoch).TotalSeconds);


            var payload = new Dictionary<string, object>
            {
                {"userName", user.userName},
                {"userId", user.Id},
                {"role", "Admin"  },
                {"sub", user.Id},
                {"nbf", notBefore},
                {"iat", issuedAt},
                {"exp", expiry}
            };

            //var secret = ConfigurationManager.AppSettings.Get("jwtKey");
            const string apikey = "secretKey";

            var token = JsonWebToken.Encode(payload, apikey, JwtHashAlgorithm.HS256);

            dbUser = new { user.userName, user.Id };
            return token;
        }
               

        /// <summary>
        ///     Creates a random salt to be used for encrypting a password
        /// </summary>
        /// <returns></returns>
        public static string CreateSalt()
        {
            var data = new byte[0x10];
            using (var cryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                cryptoServiceProvider.GetBytes(data);
                return Convert.ToBase64String(data);
            }
        }

        /// <summary>
        ///     Encrypts a password using the given salt
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public static string EncryptPassword(string password, string salt)
        {
            using (var sha256 = SHA256.Create())
            {
                var saltedPassword = string.Format("{0}{1}", salt, password);
                var saltedPasswordAsBytes = Encoding.UTF8.GetBytes(saltedPassword);
                return Convert.ToBase64String(sha256.ComputeHash(saltedPasswordAsBytes));
            }
        }
          
      
    }
}