userSSOForm.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. 'use client'
  2. import cn from 'classnames'
  3. import { useRouter, useSearchParams } from 'next/navigation'
  4. import type { FC } from 'react'
  5. import { useEffect, useState } from 'react'
  6. import { useTranslation } from 'react-i18next'
  7. import Toast from '@/app/components/base/toast'
  8. import { getUserOAuth2SSOUrl, getUserOIDCSSOUrl, getUserSAMLSSOUrl } from '@/service/sso'
  9. import Button from '@/app/components/base/button'
  10. type UserSSOFormProps = {
  11. protocol: string
  12. }
  13. const UserSSOForm: FC<UserSSOFormProps> = ({
  14. protocol,
  15. }) => {
  16. const searchParams = useSearchParams()
  17. const consoleToken = searchParams.get('console_token')
  18. const message = searchParams.get('message')
  19. const router = useRouter()
  20. const { t } = useTranslation()
  21. const [isLoading, setIsLoading] = useState(false)
  22. useEffect(() => {
  23. if (consoleToken) {
  24. localStorage.setItem('console_token', consoleToken)
  25. router.replace('/apps')
  26. }
  27. if (message) {
  28. Toast.notify({
  29. type: 'error',
  30. message,
  31. })
  32. }
  33. }, [])
  34. const handleSSOLogin = () => {
  35. setIsLoading(true)
  36. if (protocol === 'saml') {
  37. getUserSAMLSSOUrl().then((res) => {
  38. router.push(res.url)
  39. }).finally(() => {
  40. setIsLoading(false)
  41. })
  42. }
  43. else if (protocol === 'oidc') {
  44. getUserOIDCSSOUrl().then((res) => {
  45. document.cookie = `user-oidc-state=${res.state}`
  46. router.push(res.url)
  47. }).finally(() => {
  48. setIsLoading(false)
  49. })
  50. }
  51. else if (protocol === 'oauth2') {
  52. getUserOAuth2SSOUrl().then((res) => {
  53. document.cookie = `user-oauth2-state=${res.state}`
  54. router.push(res.url)
  55. }).finally(() => {
  56. setIsLoading(false)
  57. })
  58. }
  59. else {
  60. Toast.notify({
  61. type: 'error',
  62. message: 'invalid SSO protocol',
  63. })
  64. setIsLoading(false)
  65. }
  66. }
  67. return (
  68. <div className={
  69. cn(
  70. 'flex flex-col items-center w-full grow justify-center',
  71. 'px-6',
  72. 'md:px-[108px]',
  73. )
  74. }>
  75. <div className='flex flex-col md:w-[400px]'>
  76. <div className="w-full mx-auto">
  77. <h2 className="text-[32px] font-bold text-gray-900">{t('login.pageTitle')}</h2>
  78. </div>
  79. <div className="w-full mx-auto mt-10">
  80. <Button
  81. tabIndex={0}
  82. type='primary'
  83. onClick={() => { handleSSOLogin() }}
  84. disabled={isLoading}
  85. className="w-full !fone-medium !text-sm"
  86. >{t('login.sso')}
  87. </Button>
  88. </div>
  89. </div>
  90. </div>
  91. )
  92. }
  93. export default UserSSOForm