Example #1
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());
        }
Example #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));
        }
        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."
                }));
            }
        }
Example #4
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);
        }
Example #5
0
        public void Handle(CreateNewServiceCommand createNewService)
        {
            var service = new Service()
            {
                PrivateToken   = GenerateToken.Generate(24),
                PublicToken    = GenerateToken.Generate(24),
                WelcomeMessage = createNewService.WelcomeMessage
            };

            this.createNewService.Insert(service);

            createNewService.Id           = service.Id;
            createNewService.PrivateToken = service.PrivateToken;
            createNewService.PublicToken  = service.PublicToken;
        }
Example #6
0
        public IHttpActionResult Post(User user)
        {
            BaseService <User> bsu   = new BaseService <User>(new ModelStateWrapper(this.ModelState), new UnitOfWork());
            List <User>        users = bsu.GetAll();
            User loggedUser          = bsu.GetAll(u => u.Email == user.Email && u.Password == user.Password).SingleOrDefault();

            BaseService <Token> serviceToken = new BaseService <Token>(new ModelStateWrapper(this.ModelState), new UnitOfWork());
            List <Token>        tokens       = serviceToken.GetAll();
            Token token = serviceToken.GetAll(t => t.UserId == loggedUser.Id).SingleOrDefault();

            if (tokens.Count == 0 || !tokens.Contains(serviceToken.GetAll(t => t.UserId == loggedUser.Id).SingleOrDefault()))
            {
                Token Newtoken = new Token()
                {
                    Name      = GenerateToken.Generate(),
                    UserId    = loggedUser.Id,
                    StartDate = DateTime.Now
                };
                Newtoken.EndDate = Newtoken.StartDate.AddMinutes(30);
                service.Create(Newtoken);
                service.Save();
                return(Ok(Newtoken.Name));
            }

            if (token.EndDate >= DateTime.Now)
            {
                HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.NotImplemented);
                message.Content = new StringContent("This user already have a generated token - " + token.Name);
                throw new HttpResponseException(message);
            }
            else
            {
                serviceToken.Delete(token.Id);
                serviceToken.Save();
                Token newToken = new Token()
                {
                    Name      = GenerateToken.Generate(),
                    UserId    = loggedUser.Id,
                    StartDate = DateTime.Now
                };
                newToken.EndDate = newToken.StartDate.AddMinutes(30);
                service.Create(newToken);
                service.Save();
                return(Ok(newToken.Name));
            }
        }
Example #7
0
        public IActionResult Create([Bind("DeviceId, Name, ChipId,Description")] Device device)
        {
            var LoginUserId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (LoginUserId == null)
            {
                ViewBag.ErrorMessage = $"User with Id = {LoginUserId} cannot be found";
                return(View("NotFound"));
            }
            device.CreatedBy   = LoginUserId;
            device.UpdatedBy   = LoginUserId;
            device.WriteAPIKey = GenerateToken.Generate();
            device.ReadAPIKey  = GenerateToken.Generate();
            if (ModelState.IsValid)
            {
                _context.Add(device);
                _context.SaveChanges();
                return(RedirectToAction(nameof(Index)));
            }
            return(View(device));
        }
Example #8
0
        public ActionResult Insert([FromBody] string welcomeMessage)
        {
            var service = new CreateNewServiceCommand()
            {
                Service = new Service()
                {
                    PrivateToken   = GenerateToken.Generate(24),
                    PublicToken    = GenerateToken.Generate(24),
                    WelcomeMessage = welcomeMessage
                }
            };

            try
            {
                handler.Handle(service);
                return(Created(service.Service.Id, service.Service));
            }
            catch
            {
                return(BadRequest());
            }
        }
Example #9
0
        public async Task <IActionResult> Register(
            [FromBody] RegisterUserRequest request,
            [FromServices] SigningConfigurations signingConfigurations,
            [FromServices] TokenConfigurations tokenConfigurations)
        {
            try
            {
                var response = await _mediator.Send(request, CancellationToken.None);

                if (response.Success == true)
                {
                    response.Data = GenerateToken.Generate(response, signingConfigurations, tokenConfigurations);
                    return(await ResponseSaveAsync(response));
                }

                return(ResponseGet(response));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #10
0
        public IActionResult GetToken([FromBody] DAL.Models.AuthUser user)
        {
            string secretSection = Configuration.GetSection("AppSettings").GetSection("Secret").Value;

            string token = GenerateToken.Generate(new TokenDescriptor
            {
                Claims = new Claim[]
                {
                    new Claim("userName", user.UserName),
                    new Claim("password", user.Password),
                    new Claim("email", "*****@*****.**"),
                    new Claim("country", "Türkiye"),
                    new Claim(ClaimTypes.Role, "Admin")
                },
                ExpiresValue = DateTime.UtcNow.AddMinutes(1),
                Secret       = secretSection
            });

            return(new JsonResult(new
            {
                Token = token
            }));
        }
Example #11
0
        public LoginResponseModel Login(LoginRequestModel loginRequestModel)
        {
            _nLogLogger.Trace("Start", "Login Controller");
            var loginResults = this.loginService.Login(loginRequestModel, this.ActionContext.Request.Headers.Host);

            _nLogLogger.Trace("After Login Call", "Login Controller");

            if (loginResults.Success)
            {
                _nLogLogger.Trace("Before Business Rules", "Login Controller");
                this.DoBusinessRules(loginResults);
                _nLogLogger.Trace("After Business Rules", "Login Controller");

                var token = GenerateToken.Generate(_nLogLogger);
                if (token != "")
                {
                    bool error;
                    var  uriBuilder   = new UriBuilder(loginResults.RestAccessUrl + "/web/api/sa/SaGetEnv");
                    var  saGetRequest = new SaGetEnvResponse
                    {
                        ttblsaenv = new Ttblsaenv
                        {
                            dateformat = ""
                        }
                    };
                    var webHeaderCollection = new WebHeaderCollection
                    {
                        { "Token", token },
                        { "Accept-Encoding", "gzip, deflate" },
                        { "Accept", "application/json" },
                        { "Content-Type", "application/json" }
                    };
                    var responseObject = MakeWebCall.DoWebCallString <SaGetEnvResponse>(uriBuilder.Uri, true,
                                                                                        JsonConvert.SerializeObject(saGetRequest), webHeaderCollection, out error, _nLogLogger);
                    if (!error)
                    {
                        loginResults.DateFormat = responseObject.ttblsaenv.dateformat;
                    }
                    else
                    {
                        _nLogLogger.Error("Failed to get environment");
                    }

                    uriBuilder = new UriBuilder(loginResults.RestAccessUrl + "/web/api/shared/logintimezone");
                    var tokenObject          = GenerateToken.ReturnToken();
                    var loginZoneTimeRequest = new LoginZoneTimeRequest
                    {
                        ttbllogintimezone = new Ttbllogintimezone
                        {
                            cono          = tokenObject.Cono,
                            oper2         = tokenObject.Oper,
                            sessionid     = tokenObject.SessionidGuid,
                            logintimezone = loginRequestModel.OffsetTime
                        }
                    };

                    MakeWebCall.DoWebCallString <string>(uriBuilder.Uri, true,
                                                         JsonConvert.SerializeObject(loginZoneTimeRequest), webHeaderCollection, out error, _nLogLogger, true);
                    if (error)
                    {
                        _nLogLogger.Error("Failed to set timezone");
                    }
                }
            }
            return(loginResults);
        }