/// <summary>
        /// Method takes Product object as input for Pushing Data on Web Server
        /// </summary>
        /// <param name="Product"></param>
        public void DataPusher(Product Product)
        {
            try
            {
                using (var client = new WebClient())
                {
                    string ClientToken = ConfigurationManager.AppSettings["CLientIDToken"].ToString();
                    Uri    URI         = new Uri(ConfigurationManager.AppSettings["LiveURI"].ToString());
                    client.Headers.Add("Content-Type:application/json");
                    client.Headers.Add("Accept:application/json");

                    //Token APIKEY
                    client.Headers.Add("APIKEY",
                                       GenerateToken.CreateToken(ShareObject.Username, ClientToken, DateTime.Now.Ticks));
                    //Setting Call back method
                    client.UploadStringCompleted += new UploadStringCompletedEventHandler(Callback);

                    //key and IV
                    string keyValue = ConfigurationManager.AppSettings["keyValue"].ToString();
                    string IVValue  = ConfigurationManager.AppSettings["IVValue"].ToString();

                    //Serializing Object
                    string SerializeData = JsonConvert.SerializeObject(Product);
                    //Encrypting Serialized Object
                    byte[] buffer = EncryptionDecryptorTripleDES.Encryption(SerializeData, keyValue, IVValue);

                    //Converting bytes To Base64String and then Upload data
                    client.UploadStringAsync(URI, Convert.ToBase64String(buffer));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 2
0
        public async Task <string> Login(Credential credential)
        {
            await DatabaseFunctions.InitializeStaticStorage(_db).ConfigureAwait(false);

            if (credential is null)
            {
                return("false");
            }

            credential.CredentialsUsername = credential.CredentialsUsername.ToLower();
            var credentialQueryingList = await DatabaseFunctions.GetCredentials(_db, credential).ConfigureAwait(false);

            if (credentialQueryingList.Count == 0)
            {
                return("false");
            }

            var passwordSalt = await DatabaseFunctions.GetPasswordSalt(_db, credential).ConfigureAwait(false);

            var passwordInDatabase = await DatabaseFunctions.GetPasswordFromDb(_db, credential).ConfigureAwait(false);

            var decryptPassword = HashServices.Decrypt(passwordSalt, credential.CredentialsPassword);

            return(!decryptPassword.Equals(passwordInDatabase) ? "false" : GenerateToken.Generate(credential.CredentialsUsername, _jwtSettings));
        }
Ejemplo n.º 3
0
        public ActionResult GetToken([Bind(Include = "Username,Password")] UserDto user)
        {
            User result = null;

            //checks if username is empty
            if (!string.IsNullOrWhiteSpace(user.UserName))
            {
                result = _userRepository.GetUserMyUserName(user.UserName);
            }

            //checks if any user was found or not.
            if (result is null)
            {
                ViewBag.Message = "Not Exist!";
                return(View(user));
            }

            //checks user password
            if (result.Password == user.PassWord)
            {
                ViewBag.Token = GenerateToken.TokenGenerate(result);
            }
            else
            {
                ViewBag.Message = "Wrong Password!";
            }

            return(View(user));
        }
Ejemplo n.º 4
0
        private async Task <LoginToResponse> Login(UserToLogin userLogin, SigningConfigurations signingConfigurations, TokenConfiguration tokenConfigurations)
        {
            if (userLogin.Email.IsEmail() && !string.IsNullOrEmpty(userLogin.Password))
            {
                var repository = UserRepository.GetInstance(_context);

                var user = await repository.GetUserLogin(userLogin.Email, userLogin.Password);

                if (user != null)
                {
                    var token = GenerateToken.TokenGenerate(user.Email, signingConfigurations, tokenConfigurations);

                    var userDisplay = user.ToDisplay();

                    if (user.Admin)
                    {
                        var repositoryBusiness = EstablishmmentRepository.GetInstance(_context);

                        userDisplay.Establishmments = repositoryBusiness.GetByAdmin(user.Id).ToDisplay();
                    }

                    return(LoginToResponse.Create(userDisplay, token));
                }
            }
            return(null);
        }
Ejemplo n.º 5
0
        public async Task<IActionResult> Post([FromBody] UserResolver model)
        {
            if (string.IsNullOrEmpty(model.Email))
                NotifierError("email empty.");

            var response = new object();

            // Recupera o usuário
            var userApplication = await user.GetByEmail(model.Email);

            // Verifica se o usuário existe
            if (userApplication == null)
                NotifierError("user not found or without permission.");

            else
            {
                // Gera o Token
                model.Email = userApplication.Email.EmailAddress;
                var token = GenerateToken.GetToken(model);

                response = new
                {
                    email = model.Email,
                    name = userApplication.Name.FullName,
                    token = token
                };
            }


            return CustomResponse(response);
        }
Ejemplo n.º 6
0
        public IActionResult OnPost(string inputURL)
        {
            if (inputURL == null)
            {
                ViewData["NullError"] = "URL input cannot be blank.";
                return(Page());
            }
            else if (!inputURL.StartsWith("http"))
            {
                inputURL = "http://" + inputURL;
            }

            string token = GenerateToken.Generate();

            while (urlData.GetShortURLByToken(token) != null)
            {
                token = token = GenerateToken.Generate();
            }

            ShortURL = new ShortURL()
            {
                URL = inputURL, Token = token
            };
            urlData.AddShortURL(ShortURL);

            return(Page());
        }
        public HttpResponseMessage GetTokenByUserNamePassword(string UserName, string Password)
        {
            ApplicationContext   db     = new ApplicationContext(new SystemUser());
            ApplicationDbContext userdb = new ApplicationDbContext();
            var userinfo = userdb.Users.FirstOrDefault(p => p.UserName == UserName);

            if (userinfo != null)
            {
                var            user      = userinfo;
                PasswordHasher ph        = new PasswordHasher();
                string         hashedpwd = ph.HashPassword(Password);
                var            result    = ph.VerifyHashedPassword(user.PasswordHash, Password);
                if (result.ToString() == "Success")
                {
                    var obj = db.ApiTokens.FirstOrDefault(p => p.T_UsersID == userinfo.Id);
                    if (obj != null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, obj));
                    }
                    else
                    {
                        var token = GenerateToken.GetToken(userinfo.Id);
                        return(Request.CreateResponse(HttpStatusCode.OK, token));
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.NotFound, "Invalid Password !"));
            }
            return(Request.CreateResponse(HttpStatusCode.NotFound, "Invalid Username/Password"));
        }
Ejemplo n.º 8
0
        public async Task <IHttpActionResult> GetTokenByUserNamePassword(string UserName, string Password)
        {
            ApplicationContext   db     = new ApplicationContext(new SystemUser());
            ApplicationDbContext userdb = new ApplicationDbContext();
            var userinfo = await userdb.Users.FirstOrDefaultAsync(p => p.UserName == UserName);

            if (userinfo != null)
            {
                var            user      = userinfo;
                PasswordHasher ph        = new PasswordHasher();
                string         hashedpwd = ph.HashPassword(Password);
                var            result    = ph.VerifyHashedPassword(user.PasswordHash, Password);
                if (result.ToString() == "Success")
                {
                    var obj = await db.ApiTokens.FirstOrDefaultAsync(p => p.T_UsersID == userinfo.Id);

                    if (obj != null)
                    {
                        return(Ok(obj));
                    }
                    else
                    {
                        var token = GenerateToken.GetToken(userinfo.Id);
                        return(Ok(token));
                    }
                }
                return(BadRequest("Invalid Password !"));
            }
            return(BadRequest("Invalid Username/Password !"));
        }
Ejemplo n.º 9
0
        internal TokenProvider(Func <ILog> log, string rootUrl, string username, string password, ISerializer serializer = null, string referer = "", ICryptoProvider cryptoProvider = null, Func <HttpClient> httpClientFunc = null)
        {
            if (string.IsNullOrWhiteSpace(rootUrl))
            {
                throw new ArgumentNullException(nameof(rootUrl), "rootUrl is null.");
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException(nameof(username), "username is null.");
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(nameof(password), "password is null.");
            }

            Serializer = serializer ?? SerializerFactory.Get();

            RootUrl        = rootUrl.AsRootUrl();
            CryptoProvider = cryptoProvider ?? CryptoProviderFactory.Get();
            var httpFunc = httpClientFunc ?? HttpClientFactory.Get;

            _httpClient  = httpFunc();
            TokenRequest = new GenerateToken(username, password)
            {
                Referer = referer
            };
            UserName = username;

            _logger = log() ?? LogProvider.For <TokenProvider>();
            _logger.DebugFormat("Created new token provider for {0}", RootUrl);
        }
Ejemplo n.º 10
0
        public async Task <IHttpActionResult> AuthenticateUser(string UserName, string Password)
        {
            ApplicationDbContext UserDb = new ApplicationDbContext();
            ApplicationContext   db     = new ApplicationContext(new SystemUser());
            var ssoUsers = await UserDb.Users.FirstOrDefaultAsync(p => p.UserName == UserName);

            if (ssoUsers != null)
            {
                var            user      = ssoUsers;
                var            roles     = user.Roles;
                PasswordHasher ph        = new PasswordHasher();
                string         hashedpwd = ph.HashPassword(Password);
                var            result    = ph.VerifyHashedPassword(user.PasswordHash, Password);
                if (result.ToString() == "Success")
                {
                    var obj = await db.ApiTokens.FirstOrDefaultAsync(p => p.T_UsersID == user.Id);

                    if (obj != null)
                    {
                        return(Ok(obj.T_AuthToken));
                    }
                    else
                    {
                        var token = GenerateToken.GetToken(user.Id);
                        return(Ok(obj.T_AuthToken));
                    }
                }

                return(BadRequest("Invalid Password !"));      //Request.CreateResponse(HttpStatusCode.NotFound, "Invalid Password !");
            }
            return(BadRequest("Invalid Username/Password !")); // Request.CreateResponse(HttpStatusCode.NotFound, "Invalid Username/Password");
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> RefreshToken([FromBody] TokenRequest tokenRequest)
        {
            if (ModelState.IsValid)
            {
                GenerateToken generateToken = new GenerateToken(configuration, userManager, settings);
                var           result        = await generateToken.UpdateAndGenerateToken(tokenRequest);

                if (result == null)
                {
                    return(BadRequest(new AuthResult()
                    {
                        Errors = new List <string>()
                        {
                            "Invalid tokens"
                        },
                        Success = false
                    }));
                }

                return(Ok(result));
            }

            return(BadRequest(new AuthResult()
            {
                Errors = new List <string>()
                {
                    "Invalid payload"
                },
                Success = false
            }));
        }
Ejemplo n.º 12
0
        public async Task <ModelResponseC34Message> UpdateDocMenuC34EditAsync(ModelMenuC34 model)
        {
            ModelResponseC34Message resp = new ModelResponseC34Message();

            switch (model.agenda4term)
            {
            case "1":
            case "2":
            case "3":
            case "4":
            case "8":
            case "9":
                if (string.IsNullOrEmpty(model.tab4Group1Seq1Input1))
                {
                    resp.Status  = false;
                    resp.Message = "กรุณาตรวจสอบและลงความเห็นของกรรมการ!";
                    goto gotoRespone;
                }
                break;
            }

            model.file1name = string.IsNullOrEmpty(model.file1name) ? "" : GenerateToken.GetGuid() + Path.GetExtension(model.file1name);
            resp            = await _IDocMenuC3Repository.UpdateDocMenuC34EditAsync(model);

            if (resp.Status)
            {
                if (!string.IsNullOrEmpty(model.file1base64))
                {
                    ServerDirectorys.SaveFileFromBase64(_IEnvironmentConfig.PathDocument, FolderDocument.menuC3Tab4, model.file1name, model.file1base64);
                }
            }

gotoRespone:
            return(resp);
        }
Ejemplo n.º 13
0
        public string Login(LoginDTO data, IConfiguration config)
        {
            if (String.IsNullOrEmpty(data.Email))
            {
                throw new Exception("Email field is required!");
            }

            if (String.IsNullOrEmpty(data.Password))
            {
                throw new Exception("Password field is required!");
            }

            if (!data.Email.Contains("@"))
            {
                throw new Exception("Enter valid email!");
            }
            data.Password = Compute256Hash.ComputeSha256Hash(data.Password);
            var valid = _unitOfWork.User.Find(u => u.Password == data.Password && u.Email == data.Email && u.IsDeleted == 0).FirstOrDefault();

            if (valid != null)
            {
                var token = GenerateToken.GenerateJSONWebToken(valid, config);
                return(token);
            }
            else
            {
                throw new Exception("User not found");
            }
        }
Ejemplo n.º 14
0
        public async Task <ActionResult <User> > GetUserByAccessToken([FromBody] string accessToken)
        {
            try
            {
                string userID = GenerateToken.GetUserIdFromAccessToken(accessToken, jwtsettings);

                //return await _context.Users.Include(u => u.Role)
                //                      .Where(u => u.UserId == Convert.ToInt32(userId)).FirstOrDefaultAsync();

                var user = await userRepository.GetUserByID(Convert.ToInt32(userID));

                if (user != null)
                {
                    return(Ok(user));
                }
                else
                {
                    return(NotFound("User not found"));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// //Method is use to Validate User Credentials from Web Server Using WEB API
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        public void ValidateUserandGetResponse(string Username, string Password)
        {
            try
            {
                UserLogin objvm = new UserLogin()
                {
                    Username = Username,
                    Password = EncryptandDecryptAES.Encrypt(Password)
                };

                ShareObject.Username = Username;
                using (var client = new WebClient())
                {
                    string ClientToken = ConfigurationManager.AppSettings["CLientIDToken"].ToString();
                    string keyValue    = ConfigurationManager.AppSettings["keyValue"].ToString();
                    string IVValue     = ConfigurationManager.AppSettings["IVValue"].ToString();


                    Uri URI = new Uri(ConfigurationManager.AppSettings["LoginURI"].ToString());
                    client.Headers.Add("Content-Type:application/json");
                    client.Headers.Add("APIKEY", GenerateToken.CreateToken(Username, ClientToken, DateTime.Now.Ticks));
                    client.Headers.Add("Accept:application/json");
                    client.UploadStringCompleted += new UploadStringCompletedEventHandler(Callback);

                    string SerializeData = JsonConvert.SerializeObject(objvm);

                    byte[] buffer = EncryptionDecryptorTripleDES.Encryption(SerializeData, keyValue, IVValue);
                    client.UploadStringAsync(URI, Convert.ToBase64String(buffer));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public HttpResponseMessage AuthenticateUser(string UserName, string Password)
        {
            ApplicationDbContext UserDb = new ApplicationDbContext();
            ApplicationContext   db     = new ApplicationContext(new SystemUser());
            var ssoUsers = UserDb.Users.Where(p => p.UserName == UserName).ToList();

            if (ssoUsers != null && ssoUsers.Count > 0)
            {
                var            user      = ssoUsers[0];
                var            roles     = user.Roles;
                PasswordHasher ph        = new PasswordHasher();
                string         hashedpwd = ph.HashPassword(Password);
                var            result    = ph.VerifyHashedPassword(user.PasswordHash, Password);
                if (result.ToString() == "Success")
                {
                    var obj = db.ApiTokens.FirstOrDefault(p => p.T_UsersID == user.Id);
                    if (obj != null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, obj.T_AuthToken));
                    }
                    else
                    {
                        var token = GenerateToken.GetToken(user.Id);
                        return(Request.CreateResponse(HttpStatusCode.OK, token.T_AuthToken));
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.NotFound, "Invalid Password !"));
            }
            return(Request.CreateResponse(HttpStatusCode.NotFound, "Invalid Username/Password"));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Create a token provider to authenticate against ArcGIS Server
        /// </summary>
        /// <param name="rootUrl">Made up of scheme://host:port/site</param>
        /// <param name="username">ArcGIS Server user name</param>
        /// <param name="password">ArcGIS Server user password</param>
        /// <param name="serializer">Used to (de)serialize requests and responses</param>
        /// <param name="referer">Referer url to use for the token generation</param>
        /// <param name="useEncryption">If true then the token generation request will be encryted</param>
        public TokenProvider(String rootUrl, String username, String password, ISerializer serializer = null, String referer = "", ICryptoProvider cryptoProvider = null)
        {
            if (String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(password))
            {
                System.Diagnostics.Debug.WriteLine("TokenProvider for '" + RootUrl + "' not initialized as username/password not supplied.");
                return;
            }

            Serializer = serializer ?? SerializerFactory.Get();
            if (Serializer == null)
            {
                throw new ArgumentNullException("serializer", "Serializer has not been set.");
            }
            RootUrl        = rootUrl.AsRootUrl();
            CryptoProvider = cryptoProvider ?? CryptoProviderFactory.Get();
            TokenRequest   = new GenerateToken(username, password)
            {
                Referer = referer
            };
            UserName = username;

            _httpClient = HttpClientFactory.Get();

            System.Diagnostics.Debug.WriteLine("Created TokenProvider for " + RootUrl);
        }
Ejemplo n.º 18
0
        public IActionResult GetToken([FromBody] Employee model)
        {
            var firmaFind = _firmaService.Authorize(model.UserName, Encrypt.MD5Encrypt(model.Password));

            if (firmaFind.Item1 == "1")
            {
                string secretSection = Configuration.GetSection("AppSettings").GetSection("Secret").Value;
                string token         = GenerateToken.Generate(new TokenDescriptor
                {
                    Claims = new Claim[]
                    {
                        new Claim("id", firmaFind.Item2.FirmaID.ToString()),
                        new Claim("userName", firmaFind.Item2.FirmaKisaAd),
                        new Claim("role", firmaFind.Item2.Rol),
                        new Claim("email", firmaFind.Item2.Eposta),
                    },
                    ExpiresValue = DateTime.UtcNow.AddDays(1),
                    Secret       = secretSection
                });

                firmaFind.Item2.SonGirisTarihi = DateTime.Now;
                _firmaService.Update(firmaFind.Item2);

                return(new JsonResult(new
                {
                    Token = token,
                    Role = firmaFind.Item2.Rol,
                    UserNameSurname = firmaFind.Item2.FirmaAd,
                    DisDerinligiSayisi = firmaFind.Item2.DisDerinligiSayisi,
                }));
            }
            else if (firmaFind.Item1 == "2")
            {
                return(new JsonResult(new
                {
                    Token = "",
                    Message = firmaFind.Item2.Rol + " hesabıyla giriş yapmaya çalışıyorsunuz. Lütfen " + firmaFind.Item2.Rol + " kullanıcısı bilgileriyle giriş yapmayı deneyin."
                }));
            }
            else if (firmaFind.Item1 == "3")
            {
                return(new JsonResult(new
                {
                    Token = "",
                    Message = "Üyeliğiniz pasif durumda gözükmektedir. Lütfen iletişime geçiniz."
                }));
            }
            else
            {
                return(new JsonResult(new
                {
                    Token = "",
                    Message = "Kullanıcı adı (mail adresi) ya da şifrenizi kontrol edip, tekrar deneyin."
                }));
            }
        }
Ejemplo n.º 19
0
        public async Task <Object> Login([FromBody] LoginModel model)
        {
            var user = await userManager.FindByNameAsync(model.Email);

            if (user != null && await userManager.CheckPasswordAsync(user, model.Password))
            {
                string token = GenerateToken.CreateToken(options, user);
                return(Ok(new { token }));
            }
            return(BadRequest(new { message = "There is not valid email of password!" }));
        }
Ejemplo n.º 20
0
        public string CreateUser1([FromBody] User x)
        {
            GenerateToken token       = new GenerateToken();
            var           AccessToken = token.GenerateTokenId(x.UserName);

            x.AccessToken = AccessToken;
            IRepository repo = new DatabaseRepository();

            repo.CreateUser(x);
            return(AccessToken);
        }
Ejemplo n.º 21
0
        public IActionResult Authenticate([FromBody] AuthRequest authRequest)
        {
            var user = _userService.FindUserByUsernameAndPassword(authRequest.Username, authRequest.Password);

            if (user == null)
            {
                return(new UnauthorizedResult());
            }
            var token = GenerateToken.TokenGeneration(user);

            return(new JsonResult(new AuthResponse(user.Id.ToString(), token)));
        }
Ejemplo n.º 22
0
 public CharacterService(
     DataContext context,
     IConfiguration configuration,
     GenerateToken tokenGenerator,
     IHttpClientFactory clientFactory,
     IMapper mapper)
 {
     this.context        = context.DbContext;
     this.Configuration  = configuration;
     this.tokenGenerator = tokenGenerator;
     this.clientFactory  = clientFactory;
     this.mapper         = mapper;
 }
Ejemplo n.º 23
0
        public async Task <object> Login([FromBody] LoginViewModel model)
        {
            GenerateToken token  = new GenerateToken(_configuration);
            var           result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

            if (result.Succeeded)
            {
                var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
                return(await token.GenerateJwtToken(model.Email, appUser));
            }

            throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
        }
Ejemplo n.º 24
0
        public void Generate2Test()
        {
            TokenEntity tokenEntity = new TokenEntity();

            tokenEntity.SetCard(1111222233334444, DateTime.Now, 123);

            GenerateToken generateToken = new GenerateToken();
            var           token         = generateToken.Generate(tokenEntity);

            var verify = generateToken.Validate(token, tokenEntity);

            Assert.True(verify);
        }
Ejemplo n.º 25
0
        public async Task <ModelResponseMessageRegisterUser> AddRegisterUserAsync(EntityRegisterUser entity_model)
        {
            ModelResponseMessageRegisterUser resp = new ModelResponseMessageRegisterUser();

            var cultureInfo = new CultureInfo("en-GB");

            CultureInfo.DefaultThreadCurrentCulture   = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

            var LicenseKey = GenerateToken.GetToken();

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("sp_register_user", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@RegisterId", SqlDbType.VarChar, 100).Value    = DateTime.Now.ToString("yyyyMMdd");
                    cmd.Parameters.Add("@LicenseKey", SqlDbType.NVarChar).Value        = LicenseKey;
                    cmd.Parameters.Add("@UserId", SqlDbType.VarChar, 200).Value        = entity_model.userid;
                    cmd.Parameters.Add("@Passw", SqlDbType.NVarChar, 500).Value        = entity_model.passw;
                    cmd.Parameters.Add("@ConfirmPassw", SqlDbType.NVarChar, 500).Value = entity_model.confirmpassw;
                    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 250).Value         = entity_model.email;
                    cmd.Parameters.Add("@RegisterDate", SqlDbType.DateTime).Value      = entity_model.register_date;
                    cmd.Parameters.Add("@ExpireDate", SqlDbType.DateTime).Value        = entity_model.register_expire;

                    SqlParameter rStatus = cmd.Parameters.Add("@rStatus", SqlDbType.Int);
                    rStatus.Direction = ParameterDirection.Output;
                    SqlParameter rMessage = cmd.Parameters.Add("@rMessage", SqlDbType.NVarChar, 500);
                    rMessage.Direction = ParameterDirection.Output;
                    SqlParameter rRegisterId = cmd.Parameters.Add("@rRegisterId", SqlDbType.VarChar, 100);
                    rRegisterId.Direction = ParameterDirection.Output;

                    await cmd.ExecuteNonQueryAsync();

                    if ((int)cmd.Parameters["@rStatus"].Value > 0)
                    {
                        resp.Status     = true;
                        resp.RegisterId = cmd.Parameters["@rRegisterId"].Value.ToString();
                    }
                    else
                    {
                        resp.Message = cmd.Parameters["@rMessage"].Value.ToString();
                    }
                }
                conn.Close();
            }
            return(resp);
        }
Ejemplo n.º 26
0
 public IActionResult Login([FromBody] LoginModel user)
 {
     if (user == null)
     {
         return(BadRequest("Invalid Client Request"));
     }
     if (user.UserName == "alok" && user.Password == "alok@123")
     {
         return(Ok(new { Token = GenerateToken.GenerateJwtToken(user.UserName) }));
     }
     else
     {
         return(Unauthorized());
     }
 }
Ejemplo n.º 27
0
        public async Task <IHttpActionResult> GetTokenByUserId(string id)
        {
            ApplicationContext db = new ApplicationContext(new SystemUser());
            var obj = await db.ApiTokens.FirstOrDefaultAsync(p => p.T_UsersID == id);

            if (obj != null)
            {
                return(Ok(obj));
            }
            else
            {
                var token = GenerateToken.GetToken(id);
                return(Ok(token));
            }
        }
        public HttpResponseMessage GetTokenByUserId(string id)
        {
            ApplicationContext db = new ApplicationContext(new SystemUser());
            var obj = db.ApiTokens.FirstOrDefault(p => p.T_UsersID == id);

            if (obj != null)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, obj));
            }
            else
            {
                var token = GenerateToken.GetToken(id);
                return(Request.CreateResponse(HttpStatusCode.OK, token));
            }
        }
Ejemplo n.º 29
0
 public void GetAllAccountDetails2()
 {
     using (var client = new WebClient()) //WebClient
     {
         // URI
         Uri URI = new Uri(ServiceURI + "api/employee/1");
         client.Headers.Add("Content-Type:application/json");
         // Generating token
         client.Headers.Add("APIKEY", GenerateToken.CreateToken(IPAddress, Token, DateTime.UtcNow.Ticks));
         client.Headers.Add("Accept:application/json");
         //Setting Callback
         client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadString_Callback);
         client.DownloadString(URI);
     }
 }
        public HttpResponseMessage Authenticate(HttpRequestMessage request, [FromBody] string login, [FromBody] string password)
        {
            IGenerateToken credentials = new GenerateToken();
            User           user        = credentials.GetCredentials(login, password);

            if (user != null)
            {
                string token = credentials.CreateToken(user);
                return(request.CreateResponse(HttpStatusCode.OK, token));
            }
            else
            {
                return(request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Não autorizado"));
            }
        }