faizinfy

AccountController

Dec 13th, 2018
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 29.84 KB | None | 0 0
  1. Imports System.Globalization
  2. Imports System.Security.Claims
  3. Imports System.Threading.Tasks
  4. Imports Microsoft.AspNet.Identity
  5. Imports Microsoft.AspNet.Identity.Owin
  6. Imports Microsoft.AspNet.Identity.EntityFramework
  7. Imports Microsoft.Owin.Security
  8. Imports Owin
  9. Imports EmployeePerformanceCore
  10. Imports System.IO
  11. Imports System.Net.Mail
  12. Imports System.Net
  13. Imports System.Net.Http
  14. Imports System.Net.Http.Headers
  15. Imports System.Web.Script.Serialization
  16.  
  17. <Authorize>
  18. Public Class AccountController
  19.     Inherits Controllers.BaseController
  20.  
  21.     Private ius As IUserSession
  22.     Private iuss As IUserService
  23.     Private idb As IDataContext
  24.     Private istorages As IStorageService
  25.     Private ims As IMailService
  26.  
  27.     Private usermanager As UserManager(Of User, Integer)
  28.  
  29.     Public Sub New(_ius As IUserSession, _iuss As IUserService, _idb As IDataContext, _istorages As IStorageService, _ims As IMailService)
  30.  
  31.         Dim _userstore As New UserStore(Of User, UserIdentityRole, Integer, UserLogin, UserRole, UserClaim)(_idb)
  32.         Dim _usermanager As New UserManager(Of User, Integer)(_userstore)
  33.  
  34.         ius = _ius
  35.         iuss = _iuss
  36.         idb = _idb
  37.         istorages = _istorages
  38.         usermanager = _usermanager
  39.         ims = _ims
  40.  
  41.     End Sub
  42.  
  43.     Public Function Unauthorized(Optional returnurl As String = "") As ActionResult
  44.         Dim r As New Result
  45.         r.Errors.Add("You're not authorized to view the following page : " & returnurl)
  46.         Dim user As User = usermanager.FindByEmail(ius.currentusername)
  47.  
  48.         MHelper.showresult(r, TempData)
  49.         Return View(user.staff)
  50.     End Function
  51.  
  52.     '
  53.     ' GET: /Account/Login
  54.     <OutputCache(NoStore:=True, Duration:=0)>
  55.     <AllowAnonymous>
  56.     Public Function Login(returnUrl As String) As ActionResult
  57.         Dim model As New LoginViewModel
  58.  
  59.         If Not Request.Cookies("RememberMe") Is Nothing Then
  60.             model.UserName = Request.Cookies("RememberMe").Item("UNAME")
  61.             model.Password = Request.Cookies("RememberMe").Item("UPASS")
  62.             model.RememberMe = Convert.ToBoolean(Request.Cookies("RememberMe").Item("REMEMBER"))
  63.         End If
  64.  
  65.         If Request.IsAuthenticated Then
  66.             If Not ius Is Nothing Then
  67.                 If ius.currentuserid > 0 And ius.currentcompanyid > 0 Then
  68.                     Return RedirectToAction("UnAuthorized", New With {.returnurl = returnUrl})
  69.                 End If
  70.             End If
  71.         End If
  72.  
  73.         ViewBag.returnurl = returnUrl
  74.         Return View(model)
  75.     End Function
  76.  
  77.     '
  78.     ' POST: /Account/Login
  79.     <OutputCache(NoStore:=True, Duration:=0)>
  80.     <HttpPost>
  81.     <AllowAnonymous>
  82.     <ValidateAntiForgeryToken>
  83.     Public Async Function Login(model As LoginViewModel, returnUrl As String) As Task(Of ActionResult)
  84.         Dim r As New Result
  85.  
  86.         If model.RememberMe Then
  87.             If (Request.Browser.Cookies) Then
  88.                 If (Request.Cookies("RememberMe") Is Nothing) Then
  89.                     Response.Cookies("Remember").Expires = DateTime.Now.AddDays(30)
  90.                 End If
  91.  
  92.                 Response.Cookies("RememberMe").Item("Username") = model.UserName
  93.                 Response.Cookies("RememberMe").Item("Password") = model.Password
  94.                 Response.Cookies("RememberMe").Item("REMEMBER") = model.RememberMe
  95.             End If
  96.  
  97.         Else
  98.             Response.Cookies("RememberMe").Item("Username") = ""
  99.             Response.Cookies("RememberMe").Item("Password") = ""
  100.             Response.Cookies("RememberMe").Item("REMEMBER") = model.RememberMe
  101.         End If
  102.  
  103.         Dim appUser As User = Await usermanager.FindAsync(model.UserName, model.Password)
  104.         If appUser IsNot Nothing Then
  105.  
  106.             If appUser.isActive = UserStatus.Inactive Then
  107.                 r.Errors.Add("This user have been deactivated.")
  108.                 MHelper.showresult(r, TempData)
  109.                 Return RedirectToAction("login")
  110.             End If
  111.  
  112.             Await SignInAsync(appUser, model.RememberMe)
  113.  
  114.             appUser.logoffredirecturl = Nothing
  115.             idb.updatesave(appUser)
  116.  
  117.             MHelper.showresult(r, TempData, "Hey, " & appUser.staff.name & "! Welcome back!")
  118.             Return RedirectToLocal(returnUrl)
  119.         Else
  120.             r.Errors.Add("Username or password not found.")
  121.         End If
  122.  
  123.         MHelper.showresult(r, TempData)
  124.         Return RedirectToAction("login")
  125.     End Function
  126.  
  127.     Private Async Function SignInAsync(user As User, isPersistent As Boolean) As Task
  128.  
  129.         AuthenticationManager.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie)
  130.  
  131.         Dim identity = Await usermanager.CreateIdentityAsync(user, Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie)
  132.         identity.AddClaim(New Claim("staffid", user.staffid))
  133.         identity.AddClaim(New Claim("companyid", user.companyid))
  134.         identity.AddClaim(New Claim("companyname", user.company.name))
  135.  
  136.         Dim isSupervisor As Boolean = False
  137.         If idb.Staffs.Where(Function(a) a.isActive And a.companyid = user.companyid And a.staffsupervisorid = user.staffid).Count Then
  138.             isSupervisor = True
  139.         End If
  140.         identity.AddClaim(New Claim("isSupervisor", isSupervisor))
  141.  
  142.         If Not user.company.logo Is Nothing Then
  143.             identity.AddClaim(New Claim("companylogo", user.company.logo))
  144.         Else
  145.             identity.AddClaim(New Claim("companylogo", Url.Content("~/content/themes/assets/global/img/no-camera.png")))
  146.         End If
  147.  
  148.         'permission
  149.         For Each permission In user.EPUserRoles
  150.             If Not identity.HasClaim("permissions", permission.role.EnumRole) Then
  151.                 identity.AddClaim(New Claim("permissions", permission.role.EnumRole))
  152.             End If
  153.         Next
  154.  
  155.         AuthenticationManager.SignIn(New AuthenticationProperties() With {.isPersistent = isPersistent}, identity)
  156.     End Function
  157.  
  158.  
  159.     Private Async Function ExternalSignInAsync(user As User) As Task
  160.         AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie)
  161.  
  162.         Dim id = New ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType)
  163.         id.AddClaim(New Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", ClaimValueTypes.String))
  164.         id.AddClaim(New Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName, ClaimValueTypes.String))
  165.         id.AddClaim(New Claim(ClaimTypes.NameIdentifier, user.Id, ClaimValueTypes.String))
  166.  
  167.         id.AddClaim(New Claim("staffid", user.staffid))
  168.         id.AddClaim(New Claim("companyid", user.companyid))
  169.         id.AddClaim(New Claim("companyname", user.company.name))
  170.         If Not user.company.logo Is Nothing Then
  171.             id.AddClaim(New Claim("companylogo", user.company.logo))
  172.         Else
  173.             id.AddClaim(New Claim("companylogo", Url.Content("~/content/themes/assets/global/img/no-camera.png")))
  174.         End If
  175.  
  176.         'permission
  177.         For Each permission In user.EPUserRoles
  178.             If Not id.HasClaim("permissions", permission.role.EnumRole) Then
  179.                 id.AddClaim(New Claim("permissions", permission.role.EnumRole))
  180.             End If
  181.         Next
  182.  
  183.         AuthenticationManager.SignIn(New AuthenticationProperties() With {.IsPersistent = False}, id)
  184.     End Function
  185.  
  186.     Public Function LogOff(logoffredirecturl As String) As ActionResult
  187.         AuthenticationManager.SignOut()
  188.  
  189.         Dim r As New Result
  190.         MHelper.showresult(r, TempData, "You have successfully log out!")
  191.  
  192.         If Not String.IsNullOrEmpty(logoffredirecturl) Then
  193.             Return Redirect(logoffredirecturl)
  194.         End If
  195.  
  196.         Return RedirectToAction("Login")
  197.     End Function
  198.  
  199.     '
  200.     ' GET: /Account/Register
  201.     <AllowAnonymous>
  202.     Public Function Register() As ActionResult
  203.  
  204.         Return View()
  205.     End Function
  206.  
  207.     '
  208.     ' POST: /Account/Register
  209.     <HttpPost>
  210.     <AllowAnonymous>
  211.     <ValidateAntiForgeryToken>
  212.     Public Async Function Register(model As RegisterViewModel) As Task(Of ActionResult)
  213.         Dim r As New Result
  214.  
  215.         Dim checkemail As User = idb.Users.Where(Function(a) a.Email.Trim.ToLower = model.Email.Trim.ToLower).FirstOrDefault
  216.         If Not checkemail Is Nothing Then
  217.             r.Errors.Add("The email address have been used. Please use another email.")
  218.             MHelper.showresult(r, TempData)
  219.             Return RedirectToAction("Login")
  220.         End If
  221.  
  222.         If isEmailAddressValid(model.Email) Then
  223.             r = Await iuss.RegisterCompanyAsync(model.CompanyName, model.Email, model.StaffName, model.Password, model.ConfirmPassword)
  224.  
  225.             If r.isSuccess Then
  226.                 Dim user As User = usermanager.FindByEmail(model.Email)
  227.  
  228.                 Dim userrole As New EPUserRole
  229.                 userrole.userid = user.Id
  230.                 userrole.roleid = idb.EPRoles.Where(Function(a) a.EnumRole = EnumRole.Admin).FirstOrDefault.id
  231.                 idb.EPUserRoles.Add(userrole)
  232.  
  233.                 r = idb.save(ius.currentuserid, ius.currentcompanyid)
  234.  
  235.                 MHelper.showresult(r, TempData, "Registration completed. You may now log in.")
  236.                 Return RedirectToAction("", "")
  237.             Else
  238.                 MHelper.showresult(r, TempData)
  239.                 Return View(model)
  240.             End If
  241.         Else
  242.             r.Errors.Add("Please provide a correct email address!")
  243.             MHelper.showresult(r, TempData)
  244.             Return View(model)
  245.         End If
  246.     End Function
  247.  
  248.     Function isEmailAddressValid(ByVal emailAddress As String) As Boolean
  249.         Dim regExPattern As String = "\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z"
  250.  
  251.         If Regex.IsMatch(emailAddress, regExPattern) Then
  252.             Return True
  253.         Else
  254.             Return False
  255.         End If
  256.     End Function
  257.     '
  258.     ' GET: /Account/ConfirmEmail
  259.     <AllowAnonymous>
  260.     Public Async Function ConfirmEmail(userId As String, code As String) As Task(Of ActionResult)
  261.         If userId Is Nothing OrElse code Is Nothing Then
  262.             Return View("Error")
  263.         End If
  264.         Dim result = Await usermanager.ConfirmEmailAsync(userId, code)
  265.         Return View(If(result.Succeeded, "ConfirmEmail", "Error"))
  266.     End Function
  267.  
  268.     <HttpPost()>
  269.     <AllowAnonymous()>
  270.     Public Async Function RecoverPassword(ByVal model As ResetPasswordViewModel) As Threading.Tasks.Task(Of ActionResult)
  271.  
  272.         ViewBag.error = "0"
  273.         Dim r As New Result
  274.  
  275.         r = iuss.FindUserByUsername(model.Email)
  276.         If Not r.isSuccess Then
  277.             MHelper.showresult(r, TempData)
  278.             ViewBag.error = r.Errors.FirstOrDefault
  279.             Return RedirectToAction("login")
  280.         End If
  281.  
  282.         Dim rand As New Random
  283.         Dim newpassword As String = rand.Next(100000, 999999)
  284.         Dim successchangepassword As Boolean = False
  285.  
  286.         r = Await iuss.ResetPasswordAsync(model.Email, newpassword)
  287.         If Not r.isSuccess Then
  288.             MHelper.showresult(r, TempData)
  289.             ViewBag.error = r.Errors.FirstOrDefault
  290.             Return View()
  291.         Else
  292.             Dim user = Await usermanager.FindByNameAsync(model.Email)
  293.             Dim websiteurl As String = ConfigurationManager.AppSettings("websiteurl")
  294.  
  295.             Dim email As New Email
  296.             email.to = model.Email
  297.             email.subject = "You have successfully reset your password"
  298.             email.body = ViewRenderer.RenderView("~/views/mail/ForgotPasswordEmailTemplate.vbhtml", model:=New ForgotPasswordViewModel With {.email = model.Email, .companyname = user.company.name, .companylogo = user.company.logo, .staffname = user.staff.name, .newpassword = newpassword, .websiteurl = websiteurl})
  299.             email.isbodyhtml = True
  300.  
  301.             email.DateTimeCreatedUTC = DateTime.Now
  302.  
  303.             Dim tempr As Result = ims.SendMail(email, user.companyid)
  304.             r.AddErrorsAndWarningsOfAnotherResult(tempr)
  305.         End If
  306.  
  307.         r.Warnings.Add("Please check your email for new password.")
  308.         MHelper.showresult(r, TempData)
  309.         Return RedirectToAction("Login")
  310.     End Function
  311.  
  312.     '
  313.     ' GET: /Account/ForgotPassword
  314.     <AllowAnonymous>
  315.     Public Function ForgotPassword() As ActionResult
  316.         Return View()
  317.     End Function
  318.  
  319.     '
  320.     ' POST: /Account/ForgotPassword
  321.     <HttpPost>
  322.     <AllowAnonymous>
  323.     <ValidateAntiForgeryToken>
  324.     Public Async Function ForgotPassword(model As ForgotPasswordViewModel) As Task(Of ActionResult)
  325.         If ModelState.IsValid Then
  326.             Dim user = Await usermanager.FindByNameAsync(model.Email)
  327.             If user Is Nothing OrElse Not (Await usermanager.IsEmailConfirmedAsync(user.Id)) Then
  328.                 ' Don't reveal that the user does not exist or is not confirmed
  329.                 Return View("ForgotPasswordConfirmation")
  330.             End If
  331.             ' For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  332.             ' Send an email with this link
  333.             ' Dim code = Await UserManager.GeneratePasswordResetTokenAsync(user.Id)
  334.             ' Dim callbackUrl = Url.Action("ResetPassword", "Account", New With { .userId = user.Id, .code = code }, protocol := Request.Url.Scheme)
  335.             ' Await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=""" & callbackUrl & """>here</a>")
  336.             ' Return RedirectToAction("ForgotPasswordConfirmation", "Account")
  337.         End If
  338.  
  339.         ' If we got this far, something failed, redisplay form
  340.         Return View(model)
  341.     End Function
  342.  
  343.     '
  344.     ' GET: /Account/ForgotPasswordConfirmation
  345.     <AllowAnonymous>
  346.     Public Function ForgotPasswordConfirmation() As ActionResult
  347.         Return View()
  348.     End Function
  349.  
  350.     '
  351.     ' GET: /Account/ResetPassword
  352.     <AllowAnonymous>
  353.     Public Function ResetPassword(code As String) As ActionResult
  354.         Return If(code Is Nothing, View("Error"), View())
  355.     End Function
  356.  
  357.     '
  358.     ' POST: /Account/ResetPassword
  359.     <HttpPost>
  360.     <AllowAnonymous>
  361.     <ValidateAntiForgeryToken>
  362.     Public Async Function ResetPassword(model As ResetPasswordViewModel) As Task(Of ActionResult)
  363.         If Not ModelState.IsValid Then
  364.             Return View(model)
  365.         End If
  366.         Dim user = Await usermanager.FindByNameAsync(model.Email)
  367.         If user Is Nothing Then
  368.             ' Don't reveal that the user does not exist
  369.             Return RedirectToAction("ResetPasswordConfirmation", "Account")
  370.         End If
  371.         Dim result = Await usermanager.ResetPasswordAsync(user.Id, model.Code, model.Password)
  372.         If result.Succeeded Then
  373.             Return RedirectToAction("ResetPasswordConfirmation", "Account")
  374.         End If
  375.         AddErrors(result)
  376.         Return View()
  377.     End Function
  378.  
  379.     '
  380.     ' GET: /Account/ResetPasswordConfirmation
  381.     <AllowAnonymous>
  382.     Public Function ResetPasswordConfirmation() As ActionResult
  383.         Return View()
  384.     End Function
  385.  
  386.     '
  387.     ' POST: /Account/ExternalLogin
  388.     <HttpPost>
  389.     <AllowAnonymous>
  390.     <ValidateAntiForgeryToken>
  391.     Public Function ExternalLogin(provider As String, returnUrl As String) As ActionResult
  392.         ' Request a redirect to the external login provider
  393.         Return New ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", New With {
  394.             .ReturnUrl = returnUrl
  395.         }))
  396.     End Function
  397.  
  398.     '
  399.     ' POST: /Account/ExternalLogin
  400.  
  401.     <AllowAnonymous>
  402.     Public Async Function HRClicksExternalLoginAsync(token As String) As Task(Of ActionResult)
  403.         Dim r As New Result
  404.  
  405.         Dim username As String = ""
  406.         Try
  407.             Dim CallWebService As New MIDAServiceCheckLogin.WSCheckLoginSoapClient
  408.             username = CallWebService.CheckLogin(token)
  409.         Catch ex As Exception
  410.             r.Errors.Add(ex.Message)
  411.         End Try
  412.  
  413.         If r.isSuccess Then
  414.             If username Is Nothing Then
  415.                 r.Errors.Add("Username not found.")
  416.             Else
  417.                 username = username & "@mida.gov.my"
  418.                 Dim appUser As User = usermanager.FindByName(username)
  419.                 If appUser IsNot Nothing Then
  420.                     If appUser.isActive = UserStatus.Inactive Then
  421.                         r.Errors.Add("This user have been deactivated.")
  422.                         MHelper.showresult(r, TempData)
  423.                         Return RedirectToAction("login")
  424.                     End If
  425.  
  426.                     Await ExternalSignInAsync(appUser)
  427.  
  428.                     appUser.logoffredirecturl = "http://hr.mida.gov.my"
  429.                     idb.updatesave(appUser)
  430.  
  431.                     MHelper.showresult(r, TempData, "Hey, " & appUser.staff.name & "! Welcome back!")
  432.                     Return RedirectToAction("", "")
  433.                 Else
  434.                     r.Errors.Add("Username not found.")
  435.                 End If
  436.  
  437.             End If
  438.         End If
  439.  
  440.         MHelper.showresult(r, TempData)
  441.         Return RedirectToAction("ExternalLoginFailure")
  442.     End Function
  443.  
  444.     '
  445.     ' GET: /Account/SendCode
  446.     <AllowAnonymous>
  447.     Public Async Function SendCode(returnUrl As String, rememberMe As Boolean) As Task(Of ActionResult)
  448.         'Dim userId = Await SignInManager.GetVerifiedUserIdAsync()
  449.         'If userId Is Nothing Then
  450.         '    Return View("Error")
  451.         'End If
  452.         'Dim userFactors = Await UserManager.GetValidTwoFactorProvidersAsync(userId)
  453.         'Dim factorOptions = userFactors.[Select](Function(purpose) New SelectListItem() With {
  454.         '    .Text = purpose,
  455.         '    .Value = purpose
  456.         '}).ToList()
  457.         'Return View(New SendCodeViewModel() With {
  458.         '    .Providers = factorOptions,
  459.         '    .ReturnUrl = returnUrl,
  460.         '    .RememberMe = rememberMe
  461.         '})
  462.     End Function
  463.  
  464.     '
  465.     ' POST: /Account/SendCode
  466.     <HttpPost>
  467.     <AllowAnonymous>
  468.     <ValidateAntiForgeryToken>
  469.     Public Async Function SendCode(model As SendCodeViewModel) As Task(Of ActionResult)
  470.         'If Not ModelState.IsValid Then
  471.         '    Return View()
  472.         'End If
  473.  
  474.         '' Generate the token and send it
  475.         'If Not Await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider) Then
  476.         '    Return View("Error")
  477.         'End If
  478.         'Return RedirectToAction("VerifyCode", New With { _
  479.         '    .Provider = model.SelectedProvider,
  480.         '    .ReturnUrl = model.ReturnUrl,
  481.         '    .RememberMe = model.RememberMe
  482.         '})
  483.     End Function
  484.  
  485.     '
  486.     ' GET: /Account/ExternalLoginCallback
  487.     <AllowAnonymous>
  488.     Public Async Function ExternalLoginCallback(returnUrl As String) As Task(Of ActionResult)
  489.         'Dim loginInfo = Await AuthenticationManager.GetExternalLoginInfoAsync()
  490.         'If loginInfo Is Nothing Then
  491.         '    Return RedirectToAction("Login")
  492.         'End If
  493.  
  494.         '' Sign in the user with this external login provider if the user already has a login
  495.         'Dim result = Await SignInManager.ExternalSignInAsync(loginInfo, isPersistent := False)
  496.         'Select Case result
  497.         '    Case SignInStatus.Success
  498.         '        Return RedirectToLocal(returnUrl)
  499.         '    Case SignInStatus.LockedOut
  500.         '        Return View("Lockout")
  501.         '    Case SignInStatus.RequiresVerification
  502.         '        Return RedirectToAction("SendCode", New With {
  503.         '            .ReturnUrl = returnUrl,
  504.         '            .RememberMe = False
  505.         '        })
  506.         '    Case Else
  507.         '        ' If the user does not have an account, then prompt the user to create an account
  508.         '        ViewData!ReturnUrl = returnUrl
  509.         '        ViewData!LoginProvider = loginInfo.Login.LoginProvider
  510.         '        Return View("ExternalLoginConfirmation", New ExternalLoginConfirmationViewModel() With {
  511.         '            .Email = loginInfo.Email
  512.         '        })
  513.         'End Select
  514.     End Function
  515.  
  516.  
  517.  
  518.     '
  519.     ' POST: /Account/ExternalLoginConfirmation
  520.     <HttpPost>
  521.     <AllowAnonymous>
  522.     <ValidateAntiForgeryToken>
  523.     Public Async Function ExternalLoginConfirmation(model As ExternalLoginConfirmationViewModel, returnUrl As String) As Task(Of ActionResult)
  524.         If User.Identity.IsAuthenticated Then
  525.             Return RedirectToAction("Index", "Manage")
  526.         End If
  527.  
  528.         If ModelState.IsValid Then
  529.             ' Get the information about the user from the external login provider
  530.             Dim info = Await AuthenticationManager.GetExternalLoginInfoAsync()
  531.             If info Is Nothing Then
  532.                 Return View("ExternalLoginFailure")
  533.             End If
  534.             Dim userInfo = New User() With {
  535.               .UserName = model.Email,
  536.               .Email = model.Email
  537.           }
  538.             Dim result = Await usermanager.CreateAsync(userInfo)
  539.             If result.Succeeded Then
  540.                 result = Await usermanager.AddLoginAsync(userInfo.Id, info.Login)
  541.                 If result.Succeeded Then
  542.                     Await SignInAsync(userInfo, isPersistent:=False)
  543.                     Return RedirectToLocal(returnUrl)
  544.                 End If
  545.             End If
  546.             AddErrors(result)
  547.         End If
  548.  
  549.         ViewData!ReturnUrl = returnUrl
  550.         Return View(model)
  551.     End Function
  552.  
  553.     '
  554.     ' GET: /Account/ExternalLoginFailure
  555.     <AllowAnonymous>
  556.     Public Function ExternalLoginFailure() As ActionResult
  557.         Return View()
  558.     End Function
  559.  
  560.     Protected Overrides Sub Dispose(disposing As Boolean)
  561.         If disposing Then
  562.             If usermanager IsNot Nothing Then
  563.                 usermanager.Dispose()
  564.                 usermanager = Nothing
  565.             End If
  566.             'If _signInManager IsNot Nothing Then
  567.             '    _signInManager.Dispose()
  568.             '    _signInManager = Nothing
  569.             'End If
  570.         End If
  571.  
  572.         MyBase.Dispose(disposing)
  573.     End Sub
  574.  
  575. #Region "Helpers"
  576.     ' Used for XSRF protection when adding external logins
  577.     Private Const XsrfKey As String = "XsrfId"
  578.  
  579.     Private ReadOnly Property AuthenticationManager() As IAuthenticationManager
  580.         Get
  581.             Return HttpContext.GetOwinContext().Authentication
  582.         End Get
  583.     End Property
  584.  
  585.     Private Sub AddErrors(result As IdentityResult)
  586.         For Each [error] In result.Errors
  587.             ModelState.AddModelError("", [error])
  588.         Next
  589.     End Sub
  590.  
  591.     Private Function RedirectToLocal(returnUrl As String) As ActionResult
  592.         If Url.IsLocalUrl(returnUrl) Then
  593.             Return Redirect(returnUrl)
  594.         End If
  595.         Return RedirectToAction("Index", "Home")
  596.     End Function
  597.  
  598.     Friend Class ChallengeResult
  599.         Inherits HttpUnauthorizedResult
  600.         Public Sub New(provider As String, redirectUri As String)
  601.             Me.New(provider, redirectUri, Nothing)
  602.         End Sub
  603.  
  604.         Public Sub New(provider As String, redirect As String, user As String)
  605.             LoginProvider = provider
  606.             RedirectUri = redirect
  607.             UserId = user
  608.         End Sub
  609.  
  610.         Public Property LoginProvider As String
  611.         Public Property RedirectUri As String
  612.         Public Property UserId As String
  613.  
  614.         Public Overrides Sub ExecuteResult(context As ControllerContext)
  615.             Dim properties = New AuthenticationProperties() With {
  616.                 .RedirectUri = RedirectUri
  617.             }
  618.             If UserId IsNot Nothing Then
  619.                 properties.Dictionary(XsrfKey) = UserId
  620.             End If
  621.             context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider)
  622.         End Sub
  623.     End Class
  624. #End Region
  625.  
  626. #Region "Company"
  627.  
  628.     Public Function Company() As ActionResult
  629.         Dim c As Company = idb.Companies.Where(Function(a) a.id = ius.currentcompanyid).FirstOrDefault
  630.  
  631.         Return View(c)
  632.     End Function
  633.  
  634.     <HttpPost()>
  635.     Public Function Company(c As Company) As ActionResult
  636.         Dim old As Company = idb.Companies.Where(Function(a) a.id = ius.currentcompanyid).FirstOrDefault
  637.  
  638.         old.name = c.name
  639.         old.registrationno = c.registrationno
  640.         old.addressstreet1 = c.addressstreet1
  641.         old.addressstreet2 = c.addressstreet2
  642.         old.postcode = c.postcode
  643.         old.city = c.city
  644.         old.state = c.state
  645.         old.country = c.country
  646.         old.email = c.email
  647.         old.fax = c.fax
  648.         old.phone = c.phone
  649.         old.websiteURL = c.websiteURL
  650.  
  651.         Dim r As Result = idb.updatesave(old, ius.currentuserid, ius.currentcompanyid)
  652.  
  653.         Return RedirectToAction("Company")
  654.     End Function
  655.  
  656.     <HttpPost()>
  657.     Function UploadCompanyLogo(Optional file As HttpPostedFileBase = Nothing) As ActionResult
  658.         Dim r As New Result
  659.         Dim old As Company = idb.Companies.Where(Function(a) a.id = ius.currentcompanyid).FirstOrDefault
  660.  
  661.         If Not old.logo Is Nothing Then
  662.             Dim tempr As New Result
  663.  
  664.             Dim oldfilename As String = old.logo.Replace("https://authenticventure.blob.core.windows.net/employeeperformance/", "")
  665.             tempr = istorages.Delete(oldfilename)
  666.         End If
  667.  
  668.         If Not file Is Nothing Then
  669.             If file.ContentLength <= 0 Then
  670.                 r.Errors.Add("File length less than 0")
  671.             End If
  672.  
  673.             Dim originalfilename As String = Path.GetFileName(file.FileName)
  674.             Dim fileExtension As String = Path.GetExtension(file.FileName)
  675.  
  676.             Dim filename As String = ius.currentcompanyid & Now.Day & Now.Year & Now.Minute & Now.Millisecond
  677.  
  678.             Using file.InputStream
  679.                 Dim r2 = istorages.Save(filename + fileExtension, file.InputStream)
  680.                 r.AddErrorsAndWarningsOfAnotherResult(r2)
  681.  
  682.                 If r2.isSuccess Then
  683.                     old.logo = r2.fullurl
  684.                 End If
  685.             End Using
  686.         Else
  687.             old.logo = old.logo
  688.         End If
  689.  
  690.         r = idb.updatesave(old, ius.currentuserid, ius.currentcompanyid)
  691.  
  692.         MHelper.showresult(r, TempData)
  693.  
  694.         Return RedirectToAction("Company")
  695.     End Function
  696.  
  697.     <HttpPost()>
  698.     Public Function UpdateCompanyEmailSetting(c As Company) As ActionResult
  699.         Dim old As Company = idb.Companies.Where(Function(a) a.id = ius.currentcompanyid).FirstOrDefault
  700.  
  701.         old.usedefaultemailsetting = c.usedefaultemailsetting
  702.         old.emailport = c.emailport
  703.         old.emailhost = c.emailhost
  704.         old.emailfromaddress = c.emailfromaddress
  705.         old.emailusername = c.emailusername
  706.         If Not c.emailpassword = "******" Then
  707.             old.emailpassword = EmployeePerformance.Helpers.Encryptor.Encrypt(c.emailpassword)
  708.         End If
  709.         old.emailenablessl = c.emailenablessl
  710.  
  711.         Dim r As Result = idb.updatesave(old, ius.currentuserid, ius.currentcompanyid)
  712.         MHelper.showresult(r, TempData)
  713.  
  714.         Return Redirect(Url.Action("Company") & "#tab_3-3")
  715.     End Function
  716.  
  717.     Function UpdateBalanceScoreCalculationMethod(c As Company) As ActionResult
  718.         Dim old As Company = idb.Companies.Where(Function(a) a.id = ius.currentcompanyid).FirstOrDefault
  719.  
  720.         old.balancescorecardmethod = c.balancescorecardmethod
  721.  
  722.         Dim r As Result = idb.updatesave(old, ius.currentuserid, ius.currentcompanyid)
  723.  
  724.         If r.isSuccess Then
  725.             If c.balancescorecardmethod = EnumBalanceScorecarCalculationMethod.HundredPercentOnTarget Then
  726.                 Dim kpisettingsachievementIsTargeted As KPISettingsAchievement = idb.KPISettingsAchievements.Where(Function(a) a.companyid = ius.currentcompanyid And a.istarget = True).FirstOrDefault
  727.  
  728.                 If kpisettingsachievementIsTargeted Is Nothing Then
  729.                     Dim lastlevelkpisettingsachievement As KPISettingsAchievement = idb.KPISettingsAchievements.Where(Function(a) a.companyid = ius.currentcompanyid).OrderBy(Function(a) a.level).LastOrDefault
  730.                     If Not lastlevelkpisettingsachievement Is Nothing Then
  731.                         lastlevelkpisettingsachievement.istarget = True
  732.  
  733.                         Dim r2 As Result = idb.updatesave(lastlevelkpisettingsachievement, ius.currentuserid, ius.currentcompanyid)
  734.                         r.AddErrorsAndWarningsOfAnotherResultAsWarning(r2)
  735.                     End If
  736.                 End If
  737.             ElseIf c.balancescorecardmethod = EnumBalanceScorecarCalculationMethod.ModifiableThresholdPercent Then
  738.                 Dim kpisettingsachievements As List(Of KPISettingsAchievement) = idb.KPISettingsAchievements.Where(Function(a) a.companyid = ius.currentcompanyid).ToList
  739.  
  740.                 For Each item In kpisettingsachievements
  741.                     If item.defaultscore Is Nothing Then
  742.                         item.defaultscore = 0
  743.  
  744.                         Dim r2 As Result = idb.updatesave(item, ius.currentuserid, ius.currentcompanyid)
  745.                         r.AddErrorsAndWarningsOfAnotherResultAsWarning(r2)
  746.                     End If
  747.                 Next
  748.             End If
  749.         End If
  750.  
  751.         MHelper.showinfo("Please make sure you re-configure THRESHOLD SETTINGS in Configuration > KPIs > Level & Threshold", TempData)
  752.         MHelper.showresult(r, TempData)
  753.         Return Redirect(Url.Action("Company") & "#tab_4-4")
  754.     End Function
  755.  
  756. #End Region
  757. End Class
  758.  
  759. Public Class ResultResponse
  760.  
  761.     Public Sub New()
  762.         Me.errors = New List(Of String)
  763.         Me.warnings = New List(Of String)
  764.     End Sub
  765.  
  766.     ' capitalization matters! if API is lower-case, use lower case
  767.     Public Property isSuccess As Boolean
  768.     Public Property errors As ICollection(Of String)
  769.     Public Property warnings As ICollection(Of String)
  770. End Class
  771.  
  772. Public Class ApiHRClicksExternalLogin
  773.     Public Property username As String
  774. End Class
Advertisement
Add Comment
Please, Sign In to add comment