Example #1
0
        public async Task <ActionResult <CommandItem> > PostCommandItem([FromBody] CommandItem item)
        {
            try
            {
                _iDataSingleton.AddErrorLog(new ErrorLog()
                {
                    LogLevel    = LogLevel.Debug,
                    MsgDateTime = DateTime.Now,
                    Message     = $"{typeof(ValuesController)}:PostCommandItem => {item}"
                });

                if (!CheckCommandItem(item))
                {
                    return(NotFound());
                }

                if (item.Command.Equals(Command.CheckUser))
                {
                    if (await CreateUser(item))
                    {
                        return(Ok(new CommandItem()
                        {
                            Id = item.Id,
                            Command = item.Command,
                            CommandValue = "User created!"
                        }));
                    }
                    return(BadRequest(new CommandItem()
                    {
                        Id = item.Id,
                        Command = item.Command,
                        CommandValue = "Couldn't create user!"
                    }));
                }
                else
                {
                    if (!await CheckUser(item))
                    {
                        return(BadRequest(new CommandItem()
                        {
                            Id = item.Id,
                            Command = item.Command,
                            CommandValue = "User not allowed!"
                        }));
                    }
                }

                return(await CommandItemHandler(item));
            }
            catch (Exception e)
            {
                _iDataSingleton.AddErrorLog(new ErrorLog()
                {
                    LogLevel    = LogLevel.Error,
                    MsgDateTime = DateTime.Now,
                    Message     = $"{typeof(ValuesController)}:PostCommandItem Exception => {e}"
                });
                return(NotFound());
            }
        }
        public async Task <ActionResult <AnswerModel> > PostRegister([FromBody] AuthModel auth)
        {
            try
            {
                if (!_context.Users.Any(u => u.Name.Equals(auth.Name)))
                {
                    return(NotFound(new AnswerModel()
                    {
                        Answer = "User not found!"
                    }));
                }

                User user = await _context.Users.SingleAsync(u => u.Name.Equals(auth.Name));

                user.LastConnection = DateTime.Now;
                await _context.SaveChangesAsync();

                if (user.AccessRights == AccessRights.Register)
                {
                    string md5HashText = GetMd5Hash(user.Name + ":" + DateTime.UtcNow.ToString());
                    user.PhoneId      = md5HashText;
                    user.AccessRights = AccessRights.Allowed;
                    await _context.SaveChangesAsync();
                }
                else
                {
                    return(NotFound(new AnswerModel()
                    {
                        Answer = "User not allowed to register!"
                    }));
                }

                return(Ok(new AnswerModel()
                {
                    Answer = "User successfully registered!",
                    Data = user.PhoneId
                }));
            }
            catch (Exception e)
            {
                _iDataSingleton.AddErrorLog(new ErrorLog()
                {
                    LogLevel    = LogLevel.Error,
                    MsgDateTime = DateTime.Now,
                    Message     = $"{typeof(ValuesController)}:PostCommandItem Exception => {e}"
                });
                return(BadRequest());
            }
        }
Example #3
0
        /// <summary>
        /// Posts Data to the OpenHab Rest API
        /// </summary>
        /// <param name="itemPath"></param>
        /// <param name="value"></param>
        /// <param name="toggle">s</param>
        /// <returns></returns>
        public async Task PostData(string itemPath, string value, bool toggle = false)
        {
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("text/plain"));

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, itemPath);

            request.Content = new StringContent(value,
                                                Encoding.UTF8,
                                                "text/plain");

            await client.SendAsync(request)
            .ContinueWith(responseTask =>
            {
                _iDataSingleton.AddErrorLog(new ErrorLog()
                {
                    LogLevel    = LogLevel.Debug,
                    MsgDateTime = DateTime.Now,
                    Message     = $"{typeof(OpenHabMessageService)}:PostData => Response: {responseTask.Result}"
                });

                _iDataSingleton.GetSystemStatus().OpenHabStatus = responseTask.Result.IsSuccessStatusCode;
            });

            if (toggle && _iDataSingleton.GetSystemStatus().OpenHabStatus)
            {
                Thread.Sleep(500);
                await PostData(itemPath, "OFF");
            }
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    _iDataSingleton.AddErrorLog(new ErrorLog()
                    {
                        LogLevel    = LogLevel.Debug,
                        MsgDateTime = DateTime.Now,
                        Message     = $"{typeof(LoginModel)}:OnPostAsync => {Input.UserName} logged in."
                    });
                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    _iDataSingleton.AddErrorLog(new ErrorLog()
                    {
                        LogLevel    = LogLevel.Debug,
                        MsgDateTime = DateTime.Now,
                        Message     = $"{typeof(LoginModel)}:OnPostAsync {Input.UserName} account locked out."
                    });
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        /// <summary>
        /// Gets Data from the OpenHab Rest API
        /// </summary>
        /// <param name="itemPath"></param>
        /// <returns></returns>
        public async Task <string> GetData(string itemPath)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders
                .Accept
                .Add(new MediaTypeWithQualityHeaderValue("text/plain"));

                var result = await client.GetStringAsync(itemPath);

                return(result);
            }
            catch (Exception e)
            {
                _iDataSingleton.AddErrorLog(new ErrorLog()
                {
                    LogLevel    = LogLevel.Debug,
                    MsgDateTime = DateTime.Now,
                    Message     = $"{typeof(OpenHabMessageService)}:GetData => Exception: {e}"
                });
                return("");
            }
        }
Example #6
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);

            if (!changePasswordResult.Succeeded)
            {
                foreach (var error in changePasswordResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            _logger.LogInformation("User changed their password successfully.");
            _iDataSingleton.AddErrorLog(new ErrorLog()
            {
                LogLevel    = LogLevel.Debug,
                MsgDateTime = DateTime.Now,
                Message     = $"{typeof(ChangePasswordModel)}:OnPostAsync => {User} changed their password successfully."
            });
            StatusMessage = "Your password has been changed.";

            return(RedirectToPage());
        }
 public void AddQueueMessage(ErrorLog errorLog)
 {
     _dataSingleton.AddErrorLog(errorLog);
 }