Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
34 kB
3
Indexable
Never
//
//  LoginSignUpPageViewControllerStudent.swift
//  Testable
//
//  Created by Salman Navroz on 11/13/20.
//  Copyright © 2020 Salman Navroz. All rights reserved.
//

import UIKit
import Firebase
import GoogleSignIn
import GoogleUtilities
import CryptoKit
import AuthenticationServices

class LoginSignUpPageViewControllerStudent: UIViewController, GIDSignInDelegate {
    
    let passwordField = UITextField(frame: CGRect(x: 14, y: 38, width: 225, height: 18))
    let emailField = UITextField(frame: CGRect(x: 14, y: 38, width: 225, height: 18))
    let check = UIButton(frame: CGRect(x: 0, y: 2, width: 16, height: 16))
    let apple = UIButton(frame: CGRect(x: 20, y: 486, width: 374, height: 50))
    let google = UIButton(frame: CGRect(x: 20, y: 546, width: 374, height: 50))
    let logIn = UIButton(frame: CGRect(x: 20, y: 338, width: 374, height: 50))
    let loginLabel = UILabel(frame: CGRect(x: 0, y: 42, width: 243, height: 42))
    
    var viewHeight: CGFloat = 0
    var viewWidth: CGFloat = 0
    
//    let appleButton = ASAuthorizationAppleIDButton(type: .continue, style: .black)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        viewHeight = UIScreen.main.bounds.height
        viewWidth = UIScreen.main.bounds.width
        
        self.hideKeyboardWhenTappedAround()
        
        GIDSignIn.sharedInstance()?.presentingViewController = self
        GIDSignIn.sharedInstance().delegate = self
        
        self.view.backgroundColor = .testBlue
        
        navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
        self.extendedLayoutIncludesOpaqueBars = true
        
        let header = setUpHeader()
        let base = setUpBase()
        let bottom = setUpBottomBox()
        self.view.addSubviews([header,base, bottom])
        
        addBackgroundConstraints(viewToBeConstrained: header, x: 35, y: 73, width: 243, height: 81, centered: false)
        addBackgroundConstraints(viewToBeConstrained: base, x: 0, y: 186, width: 414, height: 710, centered: true)
        addBackgroundConstraints(viewToBeConstrained: bottom, x: 0, y: 826, width: 414, height: 70, centered: true)
    }
    
    func addBackgroundConstraints(viewToBeConstrained: UIView, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, centered: Bool) {
        
        viewToBeConstrained.translatesAutoresizingMaskIntoConstraints = false
        
        if UIDevice.current.userInterfaceIdiom == .pad {
            viewToBeConstrained.widthAnchor.constraint(equalToConstant: (width/896)*viewHeight * (1 + (viewWidth/viewHeight - 414/896)/2)).isActive = true
        } else {
            viewToBeConstrained.widthAnchor.constraint(equalToConstant: (width/414)*viewWidth).isActive = true
        }
        
        if centered {
            viewToBeConstrained.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        } else {
            viewToBeConstrained.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: (x/414)*viewWidth).isActive = true
        }
        
        viewToBeConstrained.heightAnchor.constraint(equalToConstant: (height/896)*viewHeight).isActive = true
        viewToBeConstrained.topAnchor.constraint(equalTo: view.topAnchor, constant: (y/896)*viewHeight).isActive = true
    }
    
    func addConstraints(viewToBeConstrained: UIView, viewToConstraintTo: UIView, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, biggerHeight: Bool, biggerWidth: Bool, centered: Bool, viewToCenterTo: UIView, aligned: Bool, viewToAlignTo: UIView, bottomButtons: Bool, trailing: Bool) {
        
        viewToBeConstrained.translatesAutoresizingMaskIntoConstraints = false
        
        if biggerHeight {
            viewToBeConstrained.widthAnchor.constraint(equalToConstant: (width/414)*viewWidth).isActive = true
            viewToBeConstrained.heightAnchor.constraint(equalToConstant: (height/896)*viewHeight * (1 + (viewWidth/viewHeight - 414/896)*1.5)).isActive = true
        } else if biggerWidth {
            viewToBeConstrained.widthAnchor.constraint(equalToConstant: (width/414)*viewWidth).isActive = true
            viewToBeConstrained.heightAnchor.constraint(equalToConstant: (height/896)*viewHeight).isActive = true
        } else {
            viewToBeConstrained.heightAnchor.constraint(equalToConstant: (height/896)*viewHeight).isActive = true
            viewToBeConstrained.widthAnchor.constraint(equalTo: viewToBeConstrained.heightAnchor, multiplier: (width/height)).isActive = true
        }
        
        if centered {
            viewToBeConstrained.centerXAnchor.constraint(equalTo: viewToCenterTo.centerXAnchor).isActive = true
        } else if aligned {
            viewToBeConstrained.leadingAnchor.constraint(equalTo: viewToAlignTo.leadingAnchor).isActive = true
        } else if bottomButtons {
            viewToBeConstrained.leadingAnchor.constraint(equalTo: viewToConstraintTo.leadingAnchor, constant: (x/896)*viewHeight).isActive = true
        } else if trailing {
            viewToBeConstrained.leadingAnchor.constraint(equalTo: viewToConstraintTo.trailingAnchor, constant: -(x/896)*viewHeight).isActive = true
        } else {
            viewToBeConstrained.leadingAnchor.constraint(equalTo: viewToConstraintTo.leadingAnchor, constant: (x/414)*viewWidth).isActive = true
        }
        
        if let textField = viewToBeConstrained as? UITextField {
            textField.topAnchor.constraint(equalTo: viewToConstraintTo.topAnchor, constant: (y/896)*viewHeight * (1 - (viewWidth/viewHeight - 414/896)/2)).isActive = true
        } else {
            viewToBeConstrained.topAnchor.constraint(equalTo: viewToConstraintTo.topAnchor, constant: (y/896)*viewHeight).isActive = true
        }
        
    }
    
    // Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce
    private func randomNonceString(length: Int = 32) -> String {
        precondition(length > 0)
        let charset: Array<Character> =
        Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
        var result = ""
        var remainingLength = length
        
        while remainingLength > 0 {
            let randoms: [UInt8] = (0 ..< 16).map { _ in
                var random: UInt8 = 0
                let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random)
                if errorCode != errSecSuccess {
                    fatalError("Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)")
                }
                return random
            }
            
            randoms.forEach { random in
                if remainingLength == 0 {
                    return
                }
                
                if random < charset.count {
                    result.append(charset[Int(random)])
                    remainingLength -= 1
                }
            }
        }
        
        return result
    }
    
    // Unhashed nonce.
    fileprivate var currentNonce: String?
    
    @available(iOS 13, *)
    @objc func startSignInWithAppleFlow() {
        let nonce = randomNonceString()
        currentNonce = nonce
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        request.nonce = sha256(nonce)
        print("starting apple")
        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.presentationContextProvider = self
        authorizationController.performRequests()
    }
    
    @available(iOS 13, *)
    private func sha256(_ input: String) -> String {
        let inputData = Data(input.utf8)
        let hashedData = SHA256.hash(data: inputData)
        let hashString = hashedData.compactMap {
            return String(format: "%02x", $0)
        }.joined()
        
        return hashString
    }
    
    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        
        if user == nil {
            return
        }
        
        if let authentication = user.authentication {
            let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken!, accessToken: authentication.accessToken)

            Auth.auth().signIn(with: credential, completion: { (user, error) -> Void in
                if error != nil {
                    print("Problem at signing in with google with error : \(error!)")
                } else if error == nil {
                    print("user successfully signed in through GOOGLE! uid:\(Auth.auth().currentUser!.uid)")
                    print("signed in")

                    UserDefaults.standard.set("student", forKey: "person")
                    UserDefaults.standard.synchronize()

                    self.performSegue(withIdentifier: "studentSignIntostudentTabBar", sender: self)
                }
            })
        }
        
//        let credential = GoogleAuthProvider.credential(withIDToken: user.authentication.idToken!, accessToken: user.authentication.accessToken)
//
//        Auth.auth().signIn(with: credential, completion: { (user, error) -> Void in
//            if error != nil {
//                print("Problem at signing in with google with error : \(error!)")
//            } else if error == nil {
//                print("user successfully signed in through GOOGLE! uid:\(Auth.auth().currentUser!.uid)")
//                print("signed in")
//
//                UserDefaults.standard.set("student", forKey: "person")
//                UserDefaults.standard.synchronize()
//
//                self.performSegue(withIdentifier: "studentSignIntostudentTabBar", sender: self)
//            }
//        })
        
        if let authentication = user.authentication {
            let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken!, accessToken: authentication.accessToken)

            Auth.auth().signIn(with: credential, completion: { (user, error) -> Void in
                if error != nil {
                    print("Problem at signing in with google with error : \(error!)")
                } else if error == nil {
                    print("user successfully signed in through GOOGLE! uid:\(Auth.auth().currentUser!.uid)")
                    print("signed in")

                    UserDefaults.standard.set("student", forKey: "person")
                    UserDefaults.standard.synchronize()

                    self.performSegue(withIdentifier: "studentSignIntostudentTabBar", sender: self)
                }
            })
        }
    }
    
    open func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return GIDSignIn.sharedInstance().handle(url)
    }
    
    func setUpHeader() -> UIView {
        let header = UIView(frame: CGRect(x: 35, y: 73, width: 243, height: 81))
        let backButton = UIButton(frame: CGRect(x: 2, y: 0, width: 20, height: 17))
        backButton.setImage(UIImage(named: "Leftarr"), for: .normal)
        backButton.contentMode = .scaleAspectFit
        backButton.contentHorizontalAlignment = .fill
        backButton.contentVerticalAlignment = .fill
        backButton.addTarget(self, action: #selector(self.backButtonTapped), for: .touchUpInside)
        
        loginLabel.font = UIFont(name: "Poppins-Bold", size: 28)
        loginLabel.textColor = .white
        loginLabel.text = "Login to Testable"
        header.addSubviews([backButton,loginLabel])
        
        addConstraints(viewToBeConstrained: backButton, viewToConstraintTo: header, x: 2, y: 0, width: 20, height: 17, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: loginLabel, viewToConstraintTo: header, x: 0, y: 42, width: 243, height: 42, biggerHeight: true, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        return header
    }
    
    func setUpBase() ->  UIView {
        let base = UIView(frame: CGRect(x: 0, y: 186, width: 414, height: 710))
        base.layer.cornerRadius = 30
        base.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        base.backgroundColor = .white
        let welcomeLabel = UILabel(frame: CGRect(x: 20, y: 30, width: 169, height: 33))
        welcomeLabel.font = UIFont(name: "Poppins-Bold", size: 22)
        welcomeLabel.textColor = .testBlue
        welcomeLabel.text = "Welcome Back"
        let pleaseLabel = UILabel(frame: CGRect(x: 20, y: 63, width: 254, height: 20))
        pleaseLabel.font = UIFont(name: "Poppins-Regular", size: 14)
        pleaseLabel.textColor = UIColor(red: 122.0/255.0, green: 134.0/255.0, blue: 154.0/255.0, alpha: 1.0)
        pleaseLabel.text = "Please sign in to continue"
        let logIn = UIButton(frame: CGRect(x: 20, y: 338, width: 374, height: 50))
        logIn.layer.cornerRadius = 14
        logIn.backgroundColor = .testBlue
        logIn.setTitle("Login", for: .normal)
        logIn.setTitleColor(.white, for: .normal)
        logIn.titleLabel?.font = UIFont(name: "Poppins-Medium", size: 18)
        logIn.addTarget(self, action: #selector(self.loginPressed), for: .touchUpInside)
        let apple = UIButton(frame: CGRect(x: 20, y: 486, width: 374, height: 50))
        apple.frame = CGRect(x: 20, y: 486, width: 374, height: 50)
        apple.layer.cornerRadius = 14
        apple.backgroundColor = .black
        apple.setTitle("Continue with Apple", for: .normal)
        apple.setTitleColor(.white, for: .normal)
        apple.titleLabel?.font = UIFont(name: "Poppins-SemiBold", size: 14)
        apple.addTarget(self, action: #selector(startSignInWithAppleFlow), for: .touchUpInside)
        let appleImage = UIImageView(frame: CGRect(x: 19.46, y: 12, width: 21.19, height: 25.26))
        appleImage.image = UIImage(named: "apple")
        apple.addSubview(appleImage)
        addConstraints(viewToBeConstrained: appleImage, viewToConstraintTo: apple, x: 19.46, y: 12, width: 21.19, height: 25.26, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        let google = UIButton(frame: CGRect(x: 20, y: 546, width: 374, height: 50))
        google.layer.cornerRadius = 14
        google.backgroundColor = UIColor(red: 81.0/255.0, green: 155.0/255.0, blue: 247.0/255.0, alpha: 1.0)
        google.setTitle("Continue with Google", for: .normal)
        google.setTitleColor(.white, for: .normal)
        google.titleLabel?.font = UIFont(name: "Poppins-SemiBold", size: 14)
        google.addTarget(self, action: #selector(self.googlePressed), for: .touchUpInside)
        let googleImage = UIImageView(frame: CGRect(x: 19, y: 14, width: 22, height: 22))
        googleImage.image = UIImage(named: "google")
        google.addSubview(googleImage)
        addConstraints(viewToBeConstrained: googleImage, viewToConstraintTo: google, x: 19, y: 14, width: 22, height: 22, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        let emailField = setUpEmailField()
        let passwordField = setUpPasswordField()
        let bottomButtons = setUpButtomButtons()
        base.addSubviews([welcomeLabel,pleaseLabel, emailField, passwordField, bottomButtons, logIn, apple, google])
        
        addConstraints(viewToBeConstrained: welcomeLabel, viewToConstraintTo: base, x: 20, y: 30, width: 169, height: 33, biggerHeight: false, biggerWidth: true, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: pleaseLabel, viewToConstraintTo: base, x: 20, y: 63, width: 254, height: 20, biggerHeight: true, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: emailField, viewToConstraintTo: base, x: 20, y: 113, width: 374, height: 68, biggerHeight: false, biggerWidth: false, centered: true, viewToCenterTo: base, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: passwordField, viewToConstraintTo: base, x: 20, y: 201, width: 374, height: 68, biggerHeight: false, biggerWidth: false, centered: true, viewToCenterTo: base, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: bottomButtons, viewToConstraintTo: base, x: 20, y: 285, width: 374, height: 68, biggerHeight: false, biggerWidth: false, centered: true, viewToCenterTo: base, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: logIn, viewToConstraintTo: base, x: 20, y: 338, width: 374, height: 50, biggerHeight: false, biggerWidth: false, centered: true, viewToCenterTo: base, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: apple, viewToConstraintTo: base, x: 20, y: 486, width: 374, height: 50, biggerHeight: false, biggerWidth: false, centered: true, viewToCenterTo: base, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: google, viewToConstraintTo: base, x: 20, y: 546, width: 374, height: 50, biggerHeight: false, biggerWidth: false, centered: true, viewToCenterTo: base, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        
        return base
        
    }
    
    func setUpEmailField() -> UIView {
        
        let container = UIView(frame: CGRect(x: 20, y: 113, width: 374, height: 68))
        container.layer.cornerRadius = 14
        container.layer.borderWidth = 2.5
        container.layer.borderColor = .testBlue
        let emailContainer = UIView(frame: CGRect(x: 14, y: 12, width: 57, height: 17))
        let mailImage = UIImageView(frame: CGRect(x: 0, y: 4, width: 13.3333333, height: 10))
        mailImage.image = #imageLiteral(resourceName: "envelope")
        mailImage.contentMode = .scaleAspectFit
        let emailLabel = UILabel(frame: CGRect(x: 23, y: 0, width: 34, height: 18))
        emailLabel.font = UIFont(name: "Poppins-Medium", size: 12)
        emailLabel.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5341)
        emailLabel.text = "Email"
        
        emailContainer.addSubviews([mailImage,emailLabel])
        
        addConstraints(viewToBeConstrained: mailImage, viewToConstraintTo: emailContainer, x: 0, y: 4, width: 13.3333333, height: 10, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: emailLabel, viewToConstraintTo: emailContainer, x: 23, y: 0, width: 34, height: 18, biggerHeight: false, biggerWidth: true, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        
        emailField.font = UIFont(name: "Poppins-Medium", size: 12)
        emailField.attributedPlaceholder = NSAttributedString(string: "Enter your email here", attributes: [NSAttributedString.Key.foregroundColor : UIColor(red: 105.0/255.0, green: 105.0/255.0, blue: 105.0/255.0, alpha: 0.5341)])
        container.addSubviews([emailContainer, emailField])
        
        addConstraints(viewToBeConstrained: emailContainer, viewToConstraintTo: container, x: 14, y: 12, width: 57, height: 17, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: emailField, viewToConstraintTo: container, x: 14, y: 38, width: 225, height: 18, biggerHeight: true, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        
        return container
        
        
    }
    
    func setUpPasswordField() -> UIView {
        let container = UIView(frame: CGRect(x: 20, y: 201, width: 374, height: 68))
        container.layer.cornerRadius = 14
        container.layer.borderWidth = 2.5
        container.layer.borderColor = .testBlue
        let passwordContainer = UIView(frame: CGRect(x: 14, y: 15, width: 57, height: 17))
        let lockImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 9.5, height: 12.67))
        lockImage.image = #imageLiteral(resourceName: "padlock")
        lockImage.contentMode = .scaleAspectFit
        let passwordLabel = UILabel(frame: CGRect(x: 115.0/6.0, y: 0, width: 59, height: 18))
        passwordLabel.font = UIFont(name: "Poppins-Medium", size: 12)
        passwordLabel.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5341)
        passwordLabel.text = "Password"
        
        passwordContainer.addSubviews([lockImage,passwordLabel])
        
        
        addConstraints(viewToBeConstrained: lockImage, viewToConstraintTo: passwordContainer, x: 0, y: 0, width: 9.5, height: 12.67, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: passwordLabel, viewToConstraintTo: passwordContainer, x: 115.0/6.0, y: 0, width: 59, height: 18, biggerHeight: false, biggerWidth: true, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        
        passwordField.font = UIFont(name: "Poppins-Medium", size: 12)
        passwordField.attributedPlaceholder = NSAttributedString(string: "Enter your password", attributes: [NSAttributedString.Key.foregroundColor : UIColor(red: 105.0/255.0, green: 105.0/255.0, blue: 105.0/255.0, alpha: 0.5341)])
        passwordField.isSecureTextEntry = true
        let eyeButton = UIButton(frame: CGRect(x: 336, y: 28, width: 18.47, height: 11.94))
        eyeButton.setImage(UIImage(named: "eye"), for: .normal)
        eyeButton.contentMode = .scaleAspectFit
        eyeButton.contentHorizontalAlignment = .fill
        eyeButton.contentVerticalAlignment = .fill
        eyeButton.addTarget(self, action: #selector(self.eyePressed), for: .touchUpInside)
        container.addSubviews([passwordContainer, passwordField, eyeButton])
        
        addConstraints(viewToBeConstrained: passwordContainer, viewToConstraintTo: container, x: 14, y: 15, width: 57, height: 17, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: passwordField, viewToConstraintTo: container, x: 14, y: 38, width: 225, height: 18, biggerHeight: true, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: eyeButton, viewToConstraintTo: container, x: 38, y: 28, width: 18.47, height: 11.94, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: true)
        
        return container
    }
    
    func setUpButtomButtons() -> UIView {
        let container = UIView(frame: CGRect(x: 20, y: 285, width: 374, height: 20))
        
        check.contentMode = .scaleAspectFit
        check.contentHorizontalAlignment = .fill
        check.contentVerticalAlignment = .fill
        check.isSelected = true
        check.setImage(UIImage(named: "onCheck"), for: .selected)
        check.setImage(UIImage(named: "offCheck"), for: .normal)
        check.addTarget(self, action: #selector(self.rememberPressed), for: .touchUpInside)
        let rememberLabel = UILabel(frame: CGRect(x: 24, y: 0, width: 106, height: 21))
        rememberLabel.amx_autoScaleEnabled = false
        rememberLabel.font = UIFont(name: "Poppins-Medium", size: (14/896)*viewHeight)
        rememberLabel.textColor = .testBlue
        rememberLabel.text = "Remember Me"
        let forgotButton = UIButton(frame: CGRect(x: 248, y: 0, width: 126, height: 21))
        forgotButton.setTitle("Forgot Password?", for: .normal)
        forgotButton.titleLabel?.amx_autoScaleEnabled = false
        forgotButton.titleLabel?.font = UIFont(name: "Poppins-Medium", size: (14/896)*viewHeight)
        forgotButton.setTitleColor(.testBlue, for: .normal)
        forgotButton.addTarget(self, action: #selector(self.forgotPressed), for: .touchUpInside)
        container.addSubviews([check,rememberLabel,forgotButton])
        
        addConstraints(viewToBeConstrained: check, viewToConstraintTo: container, x: 0, y: 2, width: 16, height: 16, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        addConstraints(viewToBeConstrained: rememberLabel, viewToConstraintTo: container, x: 24, y: 0, width: 106, height: 21, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: true, trailing: false)
        addConstraints(viewToBeConstrained: forgotButton, viewToConstraintTo: container, x: 248, y: 0, width: 126, height: 21, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: true, trailing: false)
        
        return container
    }
    
    func setUpBottomBox() -> UIView {
        let bottom = UIView(frame: CGRect(x: 0, y: 826, width: 414, height: 70))
        bottom.layer.cornerRadius = 20
        bottom.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        bottom.backgroundColor = .white
        bottom.layer.shadowColor = CGColor(red: 125.0/255.0, green: 125.0/255.0, blue: 125.0/255.0, alpha: 0.5)
        bottom.layer.shadowOpacity = 1
        bottom.layer.shadowOffset = CGSize(width: 0, height: 2)
        bottom.layer.shadowRadius = 10 / 2
        bottom.layer.shadowPath = nil
        let bottomContainer = UIView(frame: CGRect(x: 103, y: 15, width: 215, height: 20))
        let accountLabel = UILabel(frame: CGRect(x: 103, y: 15, width: 155, height: 20))
        accountLabel.text = "Don't have an account?"
        accountLabel.textColor = UIColor(red: 169.0/255.0, green: 169.0/255.0, blue: 186.0/255.0, alpha: 1)
        accountLabel.amx_autoScaleEnabled = false
        accountLabel.font = UIFont(name: "Poppins-Regular", size: (13/896)*viewHeight)
        let signUpButton = UIButton(frame: CGRect(x: 262, y: 15, width: 55, height: 20))
        signUpButton.setTitle("Sign Up", for: .normal)
        signUpButton.setTitleColor(UIColor(red: 98.0/255.0, green: 54.0/255.0, blue: 1.0, alpha: 1.0), for: .normal)
        signUpButton.titleLabel?.amx_autoScaleEnabled = false
        signUpButton.titleLabel?.font = UIFont(name: "Poppins-Bold", size: (13/896)*viewHeight)
        signUpButton.addTarget(self, action: #selector(self.signUpPressed), for: .touchUpInside)
        
        bottomContainer.addSubviews([accountLabel,signUpButton])
        
        addConstraints(viewToBeConstrained: accountLabel, viewToConstraintTo: bottomContainer, x: 0, y: 0, width: 155, height: 20, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: true, trailing: false)
        addConstraints(viewToBeConstrained: signUpButton, viewToConstraintTo: bottomContainer, x: 159, y: 0, width: 55, height: 20, biggerHeight: false, biggerWidth: false, centered: false, viewToCenterTo: view, aligned: false, viewToAlignTo: view, bottomButtons: true, trailing: false)
        
        bottom.addSubview(bottomContainer)
        
        addConstraints(viewToBeConstrained: bottomContainer, viewToConstraintTo: bottom, x: 103, y: 15, width: 215, height: 20, biggerHeight: false, biggerWidth: false, centered: true, viewToCenterTo: bottom, aligned: false, viewToAlignTo: view, bottomButtons: false, trailing: false)
        
        return bottom
    }
    
    
    @objc func eyePressed(sender : UIButton) {
        passwordField.isSecureTextEntry.toggle()
    }
    
    @objc func backButtonTapped(sender : UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func forgotPressed(sender : UIButton) {
        self.performSegue(withIdentifier: "logInToForgotStudent", sender: self)
    }
    
    @objc func rememberPressed(sender : UIButton) {
        check.isSelected.toggle()
    }
    
    @objc func googlePressed(sender : UIButton) {
        GIDSignIn.sharedInstance().signIn()
    }
    
    @objc func loginPressed(sender : UIButton) {
        if let email = emailField.text, let password = passwordField.text {
            Auth.auth().signIn(withEmail: email, password: password) { authResult, error in
                if let authResult = authResult {
                    let user = authResult.user
                    if user.isEmailVerified {
                        UserDefaults.standard.set("student", forKey: "person")
                        UserDefaults.standard.synchronize()
                        
                        self.performSegue(withIdentifier: "studentSignIntostudentTabBar", sender: self)
                    } else {
                        let alert = UIAlertController(title: "Alert", message: "Please confirm email", preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
                            switch action.style{
                                case .default:
                                print("default")
                                
                                case .cancel:
                                print("cancel")
                                
                                case .destructive:
                                print("destructive")
                                
                            }
                        }))
                        self.present(alert, animated: true, completion: nil)
                    }
                }
                
                if let e = error {
                    print(e)
                }
            }
        }
    }
    
    @objc func signUpPressed(sender : UIButton) {
        self.performSegue(withIdentifier: "studentSignInToStudentSignUp", sender: self)
    }
    

}



@available(iOS 13.0, *)
extension LoginSignUpPageViewControllerStudent: ASAuthorizationControllerDelegate {
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        print("authorizes")
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            guard let nonce = currentNonce else {
                fatalError("Invalid state: A login callback was received, but no login request was sent.")
            }
            guard let appleIDToken = appleIDCredential.identityToken else {
                print("Unable to fetch identity token")
                return
            }
            guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
                print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
                return
            }
            let credential = OAuthProvider.credential(withProviderID: "apple.com",
                                                      idToken: idTokenString,
                                                      rawNonce: nonce)
            Auth.auth().signIn(with: credential) { (authResult, error) in
                if (error != nil) {

                    
                                        if let fullNameA = appleIDCredential.fullName, let fullNameB = authResult?.user.displayName, fullNameB == "" {
                        let f = PersonNameComponentsFormatter()
                        let changeRequest = authResult?.user.createProfileChangeRequest()
                                            changeRequest?.displayName = f.string(from: fullNameA)
                    changeRequest?.commitChanges { error in
                      print("error saving name \(error)")
                    }
                    }
                    print("errrrrrrrrrr")
                    print(error?.localizedDescription ?? "")
                    return
                }
                
                UserDefaults.standard.set("student", forKey: "person")
                UserDefaults.standard.synchronize()
                
                self.performSegue(withIdentifier: "studentSignIntostudentTabBar", sender: self)
            }
        }
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Handle error.
        print("Sign in with Apple errored: \(error)")
    }
}

extension LoginSignUpPageViewControllerStudent : ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    }
}