본문 바로가기
📱Mobile/🔥Swift

[Swift] SwiftUI SHA256을 이용한 간단한 로그인 구현 예제

by 후누스 토르발즈 2021. 9. 28.
반응형

 

 

 

 

SHA256을 사용하여 password라는 문자열의 해쉬값을 만든다.

회원가입 절차는 없음으로 id는 "kim" 고정이고 password는 "password" 으로 고정

 

ContentView.swift

import SwiftUI
import CryptoKit

struct FieldStyle: ViewModifier {
    let lightGreyColor = Color(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, opacity: 1.0)
    func body(content: Content) -> some View {
        return content
            .padding()
            .background(lightGreyColor)
            .cornerRadius(5.0)
            .padding(.bottom, 5)
            .disableAutocorrection(true)
    }
}

struct ContentView: View {
    @State private var userId: String = ""
    @State private var password: String = ""
    @State private var isLogin: Bool = false
    @State private var showingAlert: Bool = false
    private var correctUserId: String = "kim"
    private var correctPassword: String = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"
    
    var body: some View {
        NavigationView{
            VStack{
                Text("WellCome!")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .padding(.bottom, 40)
                TextField("Userid", text: $userId)
                    .modifier(FieldStyle())
                    .autocapitalization(.none)
                SecureField("Password", text: $password){
                    login(userId, password)
                }
                    .modifier(FieldStyle())
                NavigationLink(destination: MainView(userId: self.$userId, isLogin: self.$isLogin), isActive: $isLogin){
                    Button(action: {
                        login(userId, password)
                    }
                    ){
                        Text("LOGIN")
                            .font(.headline)
                            .foregroundColor(.white)
                            .padding()
                            .frame(width: 280, height: 45)
                            .background(Color.blue)
                            .cornerRadius(10.0)
                    }
                }
                Spacer()
            }.padding()
            .padding(.top, 120)
            .ignoresSafeArea()
            .alert(isPresented: $showingAlert) {
                Alert(title: Text("불일치"), message: Text("아이디 또는 패스워드가 잘못되었습니다."), dismissButton: .default(Text("닫기")))
            }
        }
    }
    
    func login(_ userId: String, _ password: String){
        if(correctUserId == userId && correctPassword == toSHA256(password)){
            self.password = ""
            isLogin = true
        } else {
            showingAlert = true
        }
    }
    
    func toSHA256(_ password: String) -> String {
        let data = password.data(using: .utf8)
        let sha256 = SHA256.hash(data: data!)
        let shaData = sha256.compactMap{String(format: "%02x", $0)}.joined()
        return shaData
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

 

MainView.swift

import SwiftUI

struct MainView: View {
    @Binding var userId: String
    @Binding var isLogin: Bool
    
    var body: some View {
        VStack{
            Text(self.userId)
                .font(.largeTitle)
                .foregroundColor(.blue)
                .bold()
            Toggle(" LOGIN", isOn: $isLogin)
                .onChange(of: !isLogin) { value in
                    self.userId = ""
                }
                .frame(width: 130)
                .foregroundColor(.yellow)
                .padding()
        }
        .navigationBarHidden(true)
        .padding(.horizontal, 40)
    }
}

struct MainView_Previews: PreviewProvider {
    static var previews: some View {
        MainView(userId: .constant("kim"), isLogin: .constant(false))
    }
}

 

 

실행시 화면

userId: kim, password: password

 

반응형