示例#1
0
        public async Task <JsonResult> Post([FromBody] Shipment data, [FromHeader] string token)
        {
            string username;

            Models.ClientAuth client;
            Shipment          shipment;

            try
            {
                username = TokenMaster.ValidateToken(token);
                client   = _shipmentDBContext.ClientAuths
                           .Where(a => a.NAME == username)
                           .First();
                if (client.ID == data.ClientID)
                {
                    shipment = await ShipmentMaster.CreateShipment(data, _shipmentDBContext);

                    return(Json(shipment.ShipmentID));
                }
                else
                {
                    throw new System.Exception("Wrong client ID.");
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }
示例#2
0
        public async Task <JsonResult> Get(int id, [FromHeader] string token)
        {
            string mystring = "a";
            string username;
            List <Models.Shipment> list;
            bool flag;

            try
            {
                username = TokenMaster.ValidateToken(token);
                flag     = _shipmentDBContext.ClientAuths.Where(a => a.NAME == username).Count() > 0;
                if (!flag)
                {
                    list = (_shipmentDBContext.Shipments.Where(a => a.ClientID == id)).ToList();
                    return(Json(list));
                }
                else
                {
                    throw new System.Exception("Something failed along the way.");
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }
示例#3
0
        //Json Token
        private TokenMaster CreateToken(UserMaster user)
        {
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()),
                new Claim(ClaimTypes.Name, user.EmailId)
            };

            SymmetricSecurityKey key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value)
                );

            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(2),//token time
                SigningCredentials = creds
            };

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken           token        = tokenHandler.CreateToken(tokenDescriptor);
            TokenMaster             tmaster      = new TokenMaster
            {
                Token = tokenHandler.WriteToken(token),
                //if (!datetime.HasValue) return "";
                //dt = datetime.Value;
                tokenExpiresIn = Convert.ToDateTime(tokenDescriptor.Expires)
            };

            return(tmaster);
        }
示例#4
0
        public async Task <ServiceResponse <LoginResponse> > MobileUpdate(UserMobile Mobile_Res)
        {
            ServiceResponse <LoginResponse> response = new ServiceResponse <LoginResponse>();

            try
            {
                if (await MobileExists(Mobile_Res.MobileNo))
                {
                    response.Success = false;
                    response.Message = "Mobile No Already Exists";
                    return(response);
                }
                else
                {
                    UserMaster user = await _context.UserMaster.FirstOrDefaultAsync(x => x.UserId == Mobile_Res.UserId);

                    //&& !x.MobileNo.Equals(MobileExists(Mobile_Res.MobileNo))
                    user.UserId   = Mobile_Res.UserId;
                    user.MobileNo = Mobile_Res.MobileNo;
                    //Genterate Random Number
                    Random rnd    = new Random();
                    int    rvalue = rnd.Next(100000, 999999);
                    user.Otp = rvalue.ToString();
                    TokenMaster   tm        = CreateToken(user);
                    LoginResponse Login_Res = new LoginResponse();
                    Login_Res.UserId         = user.UserId;
                    Login_Res.EmailId        = user.EmailId;
                    Login_Res.Status         = user.Status;
                    Login_Res.Token          = tm.Token;
                    Login_Res.TokenExpiresIn = tm.tokenExpiresIn;// DateFormat.AddingTSeprator(tm.tokenExpiresIn);
                    Login_Res.FirstName      = user.FirstName;
                    Login_Res.LastName       = user.LastName;
                    Login_Res.MobileNo       = user.MobileNo;
                    Login_Res.UserTypeId     = user.UserTypeId;
                    Login_Res.PlanId         = user.PlanId;
                    Login_Res.AddedOn        = user.AddedOn;
                    Login_Res.UpdatedOn      = user.UpdatedOn;
                    //  response.Data = user.UserId.ToString();
                    //return jwt token
                    response.Data = Login_Res;

                    // response.Data = _mapper.Map<LoginResponse>(user);
                    //_context.UserMaster.Update(user);
                    await _context.SaveChangesAsync();

                    //Send Mail on success
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
                //response.Data = ex.Message;
            }
            return(response);
        }
示例#5
0
 public JsonResult Put([FromBody] UserToken data)
 {
     try
     {
         var token = TokenMaster.ValidateToken(data.Token);
         return(Json(token));
     }
     catch (System.Exception)
     {
         throw;
     }
 }
示例#6
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            /* Gain access to JWT secret and set token master's secret, if custom secret is not set in the configurations uses default secret */
            var secretString = Configuration.GetValue("Secret", "OGdjSzJXSkJORmFIOGRlVFdtUmFkWkx2RTY3TDhjMjlOZnNkQ0FBOHdhSGRYM2tiWVdKeXdVOTJiTlZwWnRKam1MQVFoWA==");

            TokenMaster.SetSecret(secretString);
            /* DB configuration */
            var connectionString = Configuration.GetConnectionString("ShipmentDBContext");

            services.AddEntityFrameworkNpgsql()
            .AddDbContext <ShipmentDBContext>(options =>
                                              options.UseNpgsql(connectionString, b => b.MigrationsAssembly("Shipment_Agent")));
        }
示例#7
0
 public bool AddUpdateTokenMaster(TokenMaster token)
 {
     try
     {
         var l_token = dBContext.TokenMaster.Where(x => x.UserId == token.UserId).FirstOrDefault();
         //Add token
         if (l_token == null)
         {
             try
             {
                 token.CreateDate = DateTime.Now;
                 token.UpdateDate = DateTime.Now;
                 dBContext.TokenMaster.Add(token);
                 dBContext.SaveChanges();
                 return(true);
             }
             catch (Exception ex)
             {
                 ex.SetLog("AddUpdateTokenMaster() AddFailed UserRepository()" + ex.Message, environment);
                 return(false);
             }
         }
         //Update token
         else
         {
             try
             {
                 l_token.Token                  = token.Token;
                 l_token.UpdateDate             = DateTime.Now;
                 dBContext.Entry(l_token).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                 dBContext.SaveChanges();
                 return(true);
             }
             catch (Exception ex)
             {
                 ex.SetLog("AddUpdateTokenMaster()==UpdateFailed UserRepo : " + ex.Message, environment);
                 return(false);
             }
         }
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
示例#8
0
        //public UserService(uTaxDBEntities _db, UserDetailDTO _user)
        //{
        //    db = _db;
        //    user = _user;
        //}

        public TokenDTO GenerateToken(Guid userId, string userip = "")
        {
            db = new DatabaseEntities();
            var tokenModel = new TokenDTO();

            if (userId != Guid.Empty)
            {
                string   token     = Guid.NewGuid().ToString();
                DateTime issuedOn  = DateTime.Now;
                DateTime expiredOn = DateTime.Now.AddSeconds(Convert.ToDouble(ConfigurationManager.AppSettings["TokenExpiredOn"].ToString()));
                //  string hostName = Dns.GetHostName();
                string myIP = userip;// Dns.GetHostByName(hostName).AddressList[0].ToString();

                var tokendomain = new TokenMaster
                {
                    UserId     = userId,
                    AuthToken  = token,
                    IssuedOn   = issuedOn,
                    ExpiredOn  = expiredOn,
                    IPAddress  = myIP,
                    StatusCode = EMPConstants.Active
                };

                db.TokenMasters.Add(tokendomain);
                db.SaveChanges();
                db.Dispose();

                tokenModel = new TokenDTO()
                {
                    UserId     = userId,
                    IssuedOn   = issuedOn,
                    ExpiredOn  = expiredOn,
                    AuthToken  = token,
                    StatusCode = EMPConstants.Active
                };
            }

            return(tokenModel);
        }
示例#9
0
        public async Task <ServiceResponse <LoginResponse> > Login(string username, string password)
        {
            // throw new System.NotImplementedException();
            ServiceResponse <LoginResponse> response = new ServiceResponse <LoginResponse>();
            UserMaster user = new UserMaster();

            //           UserMaster user = await _context.UserMaster.FirstOrDefaultAsync
            //    (x => x.EmailId.ToLower().Equals
            //    (
            //       username.ToLower())
            //);
            if (username.IndexOf('@') > -1)
            {
                //Validate email format
                string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                    @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                    @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                Regex re = new Regex(emailRegex);
                if (!re.IsMatch(username))
                {
                    response.Success = false;
                    //response.Message = "Emailid not valid.";
                    response.Message = "Mobile No Or Email ID not valid.";
                    return(response);
                }
                else
                {
                    user = await _context.UserMaster.FirstOrDefaultAsync
                               (x => x.EmailId.ToLower().Equals
                               (
                                   username.ToLower())
                               );
                }
            }
            else
            {
                //validate Username format
                string mobileRegex = @"^[6-9]\d{9}$";
                Regex  re          = new Regex(mobileRegex);
                if (!re.IsMatch(username))

                {
                    response.Success = false;
                    //response.Message = "Mobile No  not valid.";
                    response.Message = "Mobile No Or Email ID not valid.";
                    return(response);
                }
                else
                {
                    user = await _context.UserMaster.FirstOrDefaultAsync
                               (x => x.MobileNo.Equals
                               (
                                   Convert.ToInt64(username))
                               );
                }
            }

            LoginResponse Login_Res = new LoginResponse();

            if (user == null)
            {
                response.Success = false;
                response.Message = "User not found.";
                return(response);
            }
            else if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
            {
                response.Success = false;
                response.Message = "Wrong password";
                return(response);
            }
            else
            {
                Login_Res.UserId  = user.UserId;
                Login_Res.EmailId = user.EmailId;
                Login_Res.Status  = user.Status;
                TokenMaster tm = CreateToken(user);
                Login_Res.Token          = tm.Token;
                Login_Res.TokenExpiresIn = tm.tokenExpiresIn;// DateFormat.AddingTSeprator(tm.tokenExpiresIn);
                Login_Res.FirstName      = user.FirstName;
                Login_Res.LastName       = user.LastName;
                Login_Res.MobileNo       = user.MobileNo;
                Login_Res.UserTypeId     = user.UserTypeId;
                Login_Res.PlanId         = user.PlanId;
                Login_Res.AddedOn        = user.AddedOn;
                Login_Res.UpdatedOn      = user.UpdatedOn;
                //  response.Data = user.UserId.ToString();
                //return jwt token
                response.Data = Login_Res;
            }

            return(response);
        }