예제 #1
0
        static void GetVehicles(AuthTokenModel _auth, Account _account)
        {
            var     VehicleOverview = apiWrk.GetVehicleOverview(_account, _auth.Token);
            JObject ObjVehicles     = JObject.Parse(VehicleOverview);
            IList   Vehicles        = ObjVehicles["data"]["viewer"]["vehicles"].Children().ToList();

            foreach (var Vehicle in Vehicles)
            {
                JObject v         = JObject.Parse(Vehicle.ToString());
                string  id        = v["vehicle"]["id"].ToString();
                string  make      = v["vehicle"]["make"].ToString();
                string  model     = v["vehicle"]["model"].ToString();
                string  name      = v["vehicle"]["name"].ToString();
                int     odometer  = (int)v["vehicle"]["odometer"]["odometer"];
                string  fuelLevel = v["vehicle"]["fuelLevel"]["liter"].ToString();
                string  latitude  = v["vehicle"]["position"]["latitude"].ToString();
                string  longitude = v["vehicle"]["position"]["longitude"].ToString();

                log.LogToConsole("");
                log.LogToConsole("Id:\t\t" + id);
                log.LogToConsole("Make:\t\t" + make);
                log.LogToConsole("Model:\t\t" + model);
                log.LogToConsole("Name:\t\t" + name);
                log.LogToConsole("Odometer:\t" + odometer.ToString("#,##") + " km");
                log.LogToConsole("Fuel level:\t" + fuelLevel + " l");
                log.LogToConsole("-- Position --");
                log.LogToConsole("Latitude:\t" + latitude);
                log.LogToConsole("Longitude:\t" + longitude);
                log.LogToConsole("Google Maps:\t" + "http://maps.google.com/maps?q=" + latitude + "," + longitude);
            }
        }
예제 #2
0
        public async Task <AuthTokenModel> CreateToken(AuthTokenModel model)
        {
            var newEntity = _mapper.Map <AuthToken>(model);

            _dbContext.AuthTokens.Add(newEntity);
            await _dbContext.SaveChangesAsync();

            return(_mapper.Map <AuthTokenModel>(newEntity));
        }
        public async Task <AuthTokenResult> GetAuthToken()
        {
            string tokenKey = GetTokenKey();

            if (Tokens.TryGetValue(tokenKey, out AuthTokenResult getAuthTokenResult))
            {
                if (DateTime.UtcNow < getAuthTokenResult.Data.ExpireDateTime)
                {
                    return(getAuthTokenResult);
                }
            }

            bool shouldRefresh = PendingRefreshTokenRequests.TryAdd(tokenKey, true);

            if (!shouldRefresh)
            {
                return(getAuthTokenResult);
            }
            try
            {
                //utc timestamp
                long timestamp = Utc.GetTimestamp();

                AuthTokenModel authTokenModel = new AuthTokenModel()
                {
                    Sign = Sha256(
                        string.Concat(_getuiConfiguration.AppKey, timestamp, _getuiConfiguration.MasterSecret)),
                    Timestamp = timestamp,
                    AppKey    = _getuiConfiguration.AppKey
                };
                string requestUri = string.Concat(_getuiConfiguration.ApiVersion, "/", _getuiConfiguration.AppId,
                                                  "/auth");
                HttpResponseMessage httpResponseMessage =
                    await _client.PostAsync(requestUri, new JsonContent(authTokenModel));

                getAuthTokenResult = await httpResponseMessage.GetResultAsync <AuthTokenResult>();

                getAuthTokenResult.ClientHttpStatusCode = httpResponseMessage.StatusCode;

                Tokens[tokenKey] = getAuthTokenResult;

                _logger.LogInformation($"get auth token: {getAuthTokenResult}");
            }
            finally
            {
                PendingRefreshTokenRequests.TryRemove(tokenKey, out _);
            }

            return(getAuthTokenResult);
        }
예제 #4
0
        private async Task AuthenticateAsync()
        {
            var response = await _grooveHttpClient.PostAsync(new Uri("https://login.live.com/accesstoken.srf"), new FormUrlEncodedContent(_requestData));

            if (response.IsSuccessStatusCode)
            {
                String responseString = await response.Content.ReadAsStringAsync();

                AuthTokenModel tokenResponse = JsonConvert.DeserializeObject <AuthTokenModel>(responseString);
                AccessToken = tokenResponse;
                AccessToken.TokenExpiryDate = Convert.ToDouble(tokenResponse.ExpiresIn).UnixTimeStampToDateTime();
                _grooveHttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {AccessToken.AccessToken}");
            }
        }
예제 #5
0
        public HttpResponseMessage Logout()
        {
            AuthTokenModel returnToken = new AuthTokenModel
            {
                Token    = "",
                Errors   = new List <string>(),
                Messages = new List <string>()
                {
                    "User Logged Out"
                }
            };

            return(Request.CreateResponse(HttpStatusCode.OK, returnToken));
        }
예제 #6
0
        public async Task <AuthTokenModel> LoginAsync(LoginModel loginModel)
        {
            var user = await userManager.FindByNameAsync(loginModel.UserName);

            if (user != null && !user.IsDeleted)
            {
                var result = await signInManager.PasswordSignInAsync(user, loginModel.Password, loginModel.RememberMe, false);

                if (result.IsNotAllowed)
                {
                    throw new UnauthorizedAccessException("Your email has not been confirmed, please confirm your email address");
                }
                if (result.Succeeded)
                {
                    var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Tokens:Key"]));
                    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var claims = new[]
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                        new Claim(ClaimTypes.Role, user.IsAdmin.ToString()),
                        new Claim(CustomClaims.RememberMe, loginModel.RememberMe.ToString()),
                    };

                    var token = new JwtSecurityToken(
                        configuration["Tokens:Issuer"],
                        configuration["Tokens:Audience"],
                        claims,
                        expires: DateTime.UtcNow.AddYears(1),
                        signingCredentials: credentials
                        );

                    var generatedToken = new AuthTokenModel(token);

                    return(generatedToken);
                }
            }
            throw new AuthenticationException("Invalid usernamr or password");
        }
예제 #7
0
        public HttpResponseMessage Login(LoginUserModel userLogin)
        {
            HttpRequestHeaders headers = Request.Headers;
            // var userName = string.Empty;
            //var password = string.Empty;

            //var userName = Request.GetHeader("userName");
            //if (headers.Contains("userName"))
            //{
            //    userName = headers.GetValues("userName").First();
            //}

            //if (headers.Contains("password"))
            //{
            //    password = headers.GetValues("password").First();
            //}

            UserSecurityModel userSecurity = _authenticationServices.GetUserByUserName(userLogin.Email);

            if (userSecurity != null)
            {
                AuthenticationFunctions authenticationFunctions = new AuthenticationFunctions();

                bool successful = authenticationFunctions.ValidatePassword(userLogin.Password, userSecurity.Password);

                if (!successful)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid User or Password", Configuration.Formatters.JsonFormatter));
                }

                AuthenticationModule authentication = new AuthenticationModule();
                List <string>        roles          = new List <string>();
                foreach (RoleModel role in userSecurity.User.Roles)
                {
                    roles.Add(role.Name);
                }
                string token = authentication.GenerateTokenForUser(userSecurity, roles.ToArray());

                // Save the Security Token to the database for Audit purposes.
                _authenticationServices.UpdateLoginStatus(userSecurity.UserId, token, DateTime.Now.AddMinutes(int.Parse(InternalSettings.TokenExpirationMinutes)));

                AuthTokenModel returnToken = new AuthTokenModel()
                {
                    Token    = token,
                    Errors   = new List <string>(),
                    Messages = new List <string>()
                    {
                        "Success"
                    }
                };


                return(Request.CreateResponse(HttpStatusCode.OK, returnToken, Configuration.Formatters.JsonFormatter));
            }

            AuthTokenModel badReturnToken = new AuthTokenModel
            {
                Token  = "",
                Errors = new List <string>()
                {
                    "Invalid User Name or Password"
                },
                Messages = new List <string>()
                {
                    "Invalid Request or Missing Parameters"
                }
            };

            return(Request.CreateResponse(HttpStatusCode.BadRequest, badReturnToken));
        }