Code Monkey home page Code Monkey logo

Comments (33)

akkayanill avatar akkayanill commented on June 11, 2024 2

Yeah it worked. Grazie mille πŸ’―

Next, i'll try to handle multiple account, it'll probably work. i'll keep here updated.

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024 2

@mkeshnoda
If you succeeded with implementing multiple accounts, please add a note here for others, to prevent re-opening this issue in future.
And make sure to close issue after that.
Regards.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024 1

Edit: Finally managed to add second account. What i am trying to do haven't completed yet. I'll keep here updated and will tell how i did it.

Still not working... (Haven't tried it with Siwa yet because looks like it's not about login function)

By the way the other problem is :
After login, it fetches cookies like ds_user_id and csrfToken BUT it doesn't pass it to self.isUserLoggedIn(instagramCookies: instagramCookies!) sometimes. And i don't have any idea why is it happening.

private func login() {

    self.fetchCookies(completion: { (cookies) in
       
        if let cookies = cookies {
            for i in 0..<cookies.count {
                let cookie = cookies[i]
            }
        }
        
        let instagramCookies = cookies?.getInstagramCookies()
        self.isUserLoggedIn(instagramCookies: instagramCookies!)
    })
    
}

from swiftyinsta.

sbertix avatar sbertix commented on June 11, 2024 1

You should not use isUserLoggedIn(instagramCookies:), I left it public just because it used to, but it's not supposed to be called like that. We should definitely push an update to mark it internal or private, to prevent confusion.
You need to pass the SessionCache in the response directly to handler.login(cache:).
@mkeshnoda

from swiftyinsta.

sbertix avatar sbertix commented on June 11, 2024 1

I'm working next on "updating" (most likely just removing) the singleton interface (all the .shared static properties), in order to make more instances of APIHandler (et alia) run in parallel with different users logged in at the same time.
It shouldn't take too long. I hope I can start working on it tomorrow, and if so it should definitely be done by Monday.
So more multi-users stuff coming soon 😊
@mkeshnoda

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024 1

Just completed it. Yeah it worked. Thank you so much guys. @sbertix @TheM4hd1

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024

Let's start from beginning.

  1. Login tofirst account
  2. save cookies to your database for current userPk or username
  3. Add new account but before login, make sure to clean cookies (and for caution, re-create handler again)
HTTPCookieStorage.shared.cookies?.forEach({ (cookie) in
    HTTPCookieStorage.shared.deleteCookie(cookie)
})
  1. Login and run step 2 again
  2. whenever you wanted to switch between accounts you should clear cookies again and pass the cookie to handler.login(cache: SessionCache)

These steps should help you, although I never tried to add multiple accounts by myself.
Note: Never save cookies (important data) to userDefaults because of security reasons.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

I am doing the same but when i tap on login button to login 2nd user it still returns first user's cookies. I delete cookies but it doesn't change a thing.

I tried something with desktop google chrome today. let me explain
I logged out from my account + i deleted all cookies. But when i refreshed instagram my account was still standing there. Maybe that's what's happening to me when i am trying to login with the second account.

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024

Attach the codes here, so we can work on it and find the issue.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

These are the code in general. I delete cookies many times before loginin the other account πŸ”’ but still, when i am trying to login it returns the old cookies.
By the way it returned new account's cookies 1-2 times but it doesn't login. Idk why.

Okay, when i want to add account :
let loginVC = LoginVC() self.navigationController?.pushViewController(loginVC, animated: true) loginVC.webView.deleteAllCookies()

Inside LoginVC i have var webView = InstagramLoginWebView(frame: .zero)

override func viewDidLoad() { 
     super.viewDidLoad() webView.loadInstagramLogin(isNeedPreloadForCookieSync: false) 
     webView.loginDelegate = self  
}

Inside WebView

@objc func deleteAllCookies() {

    print("deleting all cookies")
    self.cleanEveryThing()
    
    fetchCookies { (cookies) in
        for cookie in cookies! {
            self.delete(cookie: cookie)
        }
    }
    
}
private func login() {

    self.fetchCookies(completion: { (cookies) in
       
        if let cookies = cookies {
            for i in 0..<cookies.count {
                let cookie = cookies[i]
            }
        }
        
        let instagramCookies = cookies?.getInstagramCookies()
        self.isUserLoggedIn(instagramCookies: instagramCookies!)
    })
    
}


 public func isUserLoggedIn(instagramCookies : [HTTPCookie]) {
        
        var isLogged = false
        var csrfToken = ""
       
        for i in 0..<instagramCookies.count { 
            let cookie = instagramCookies[i]
            if cookie.name == "ds_user_id" {
                isLogged = true
            }
            
            if cookie.name == "csrftoken" {
                csrfToken = cookie.value
            }
        }

        
        if isLogged {
            
            let _urlSession = URLSession(configuration: .default)
            let user = SessionStorage.create(username: "username", password: "password")
            
            let instagramHandler = try! APIBuilder()
                .createBuilder()
                .setHttpHandler(urlSession: _urlSession)
                .setRequestDelay(delay: .default)
                .setUser(user: user)
                .build()
            
            
            let sessionCache = SessionCache.init(user: HandlerSettings.shared.user!, device: HandlerSettings.shared.device!, requestMessage: HandlerSettings.shared.request!, cookies: (HTTPCookieStorage.shared.cookies?.getInstagramCookies()?.toCookieData())!, isUserAuthenticated: true)
            
            let cookieler = (HTTPCookieStorage.shared.cookies?.getInstagramCookies())!
            for i in 0..<cookieler.count {
                let cookie = cookieler[i]
            }
        
            try? instagramHandler.login(cache: sessionCache, completion: { (result) in })
            
            if self.loginDelegate != nil {
                self.loginDelegate?.userLoggedSuccessfully()
            }
            
            InstaEndPoint.sharedInstance.handler = instagramHandler
            self.getUser(handler: instagramHandler, csrfToken: csrfToken)
           
        } else { //user didn't logged in
        }
        
    }
func storeCookies(forKeyUserPk: String) {
        
        let cookiesStorage = HTTPCookieStorage.shared
        let userDefaults = UserDefaults.standard
        
        var cookieDict = [String : AnyObject]()
        
        for cookie in cookiesStorage.cookies(for: try! URLs.getInstagramCookieUrl())! {
            cookieDict[cookie.name] = cookie.properties as AnyObject?
        }
        
        userDefaults.set(cookieDict, forKey: forKeyUserPk)
        userDefaults.synchronize()
    }

  func restoreCookies(forKeyUserPk: String) {
       
       let cookiesStorage = HTTPCookieStorage.shared
       let userDefaults = UserDefaults.standard
   
       if let cookieDictionary = userDefaults.dictionary(forKey: forKeyUserPk) {
           
           for (_, cookieProperties) in cookieDictionary {
               if let cookie = HTTPCookie(properties: cookieProperties as! [HTTPCookiePropertyKey : Any] ) {
                   self.set(cookie: cookie)
                   cookiesStorage.setCookie(cookie)
               }
           }
       }
   }

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024

Every time you call loadInstagramLogin function, cookie deleting handled automatically. so you don't need to call it.
set isNeedPreloadForCookieSync = true and every time you want to show webView do something like this:

self.loginWebView = nil
self.loginWebView = InstagramLoginWebView(frame: CGRect.zero)
self.view.addSubview(self.loginWebView!)
// setup constraints
self.loginWebView?.loginDelegate = self
self.loginWebView?.loadInstagramLogin(isNeedPreloadForCookieSync: true)

If it doesn't help, try to use Siwa framework for login for now. and I will double check the web issue.
Tell me if it works.

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024

SwiftyInsta used WKCookieWebView as an embedded browser to handling cookies.
I looked at the original repo and it seems it is a known issue and I guess it fixed.
SwiftyInsta doesn't use the latest update of the WKCookieWebView and I think this is the problem.

As the Author said:

After running the app, before the first webview was loaded,
Cookies may not be set properly,
In that case, use the loader in advance to synchronize.

WKCookieWebView.preloadWithDomainForCookieSync(urlString: String, completion: (() -> Void)?)

I guess updating the WKCookieWebView will help to fix it.
I'm a little busy for now to doing this update, I'll appreciate if you test it.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

Edit: I'll try it with Siwa and i'll update this comment
Edit2: I can't even login with Siwa framework. It returns .inccorrectPassword, .invalidUsername errors..

Okay, i was able to add second account. But when i am trying to switch between accounts i can't login the account that i am trying to switch in.
(i pass correct cookies inside isUserLoggedIn(instagramCookies : [HTTPCookie]) func )

try instagramHandler.login(cache: sessionCache) { (result) in
result.isSucceeded coming as false when i am trying to switch to other account

public func isUserLoggedIn(instagramCookies : [HTTPCookie]) {
        
        var isLogged = false
        var csrfToken = ""
        

        for i in 0..<instagramCookies.count { 
            let cookie = instagramCookies[i]
            if cookie.name == "ds_user_id" {
                isLogged = true
            }
            
            if cookie.name == "csrftoken" {
                csrfToken = cookie.value
            }
        }

        if isLogged {
            
            let _urlSession = URLSession(configuration: .default)
            let user = SessionStorage.create(username: "username", password: "password")
            
            let instagramHandler = try! APIBuilder()
                .createBuilder()
                .setHttpHandler(urlSession: _urlSession)
                .setRequestDelay(delay: .default)
                .setUser(user: user)
                .build()
        
            let sessionCache = SessionCache.init(user: HandlerSettings.shared.user!, device: HandlerSettings.shared.device!, requestMessage: HandlerSettings.shared.request!, cookies: (instagramCookies.toCookieData()), isUserAuthenticated: true)
            
//            try? instagramHandler.login(cache: sessionCache, completion: { (result) in })

            do {
                
                try instagramHandler.login(cache: sessionCache) { (result) in
                    if  result.isSucceeded {
                        print("\n\n LOGGED IN  \n\n")
                        if self.loginDelegate != nil {
                            self.loginDelegate?.userLoggedSuccessfully()
                        }
                        
                        InstaEndPoint.sharedInstance.handler = instagramHandler

                        self.getUser(instagramCookies: instagramCookies, handler: instagramHandler, csrfToken: csrfToken)
                    } else {
                        print("login failed")
                    }
                }
            } catch {
                print("LOGIN ERROR")
            }
            
        } else { 

        }
        
    }
    

from swiftyinsta.

RealOlympusDev avatar RealOlympusDev commented on June 11, 2024

Edit: I'll try it with Siwa and i'll update this comment
Edit2: I can't even login with Siwa framework. It returns .inccorrectPassword, .invalidUsername errors..

Okay, i was able to add second account. But when i am trying to switch between accounts i can't login the account that i am trying to switch in.
(i pass correct cookies inside isUserLoggedIn(instagramCookies : [HTTPCookie]) func )

try instagramHandler.login(cache: sessionCache) { (result) in
result.isSucceeded coming as false when i am trying to switch to other account

public func isUserLoggedIn(instagramCookies : [HTTPCookie]) {
        
        var isLogged = false
        var csrfToken = ""
        

        for i in 0..<instagramCookies.count { 
            let cookie = instagramCookies[i]
            if cookie.name == "ds_user_id" {
                isLogged = true
            }
            
            if cookie.name == "csrftoken" {
                csrfToken = cookie.value
            }
        }

        if isLogged {
            
            let _urlSession = URLSession(configuration: .default)
            let user = SessionStorage.create(username: "username", password: "password")
            
            let instagramHandler = try! APIBuilder()
                .createBuilder()
                .setHttpHandler(urlSession: _urlSession)
                .setRequestDelay(delay: .default)
                .setUser(user: user)
                .build()
        
            let sessionCache = SessionCache.init(user: HandlerSettings.shared.user!, device: HandlerSettings.shared.device!, requestMessage: HandlerSettings.shared.request!, cookies: (instagramCookies.toCookieData()), isUserAuthenticated: true)
            
//            try? instagramHandler.login(cache: sessionCache, completion: { (result) in })

            do {
                
                try instagramHandler.login(cache: sessionCache) { (result) in
                    if  result.isSucceeded {
                        print("\n\n LOGGED IN  \n\n")
                        if self.loginDelegate != nil {
                            self.loginDelegate?.userLoggedSuccessfully()
                        }
                        
                        InstaEndPoint.sharedInstance.handler = instagramHandler

                        self.getUser(instagramCookies: instagramCookies, handler: instagramHandler, csrfToken: csrfToken)
                    } else {
                        print("login failed")
                    }
                }
            } catch {
                print("LOGIN ERROR")
            }
            
        } else { 

        }
        
    }
    

Also having this problem

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024

@mkeshnoda
@RealOlympusDev
When you pass the second cookie to instagramHandler.login(cache: sessionCache) what is the error when it returns false?
My guess is you are receiving user must be authenticated. error.
I faced this error when I was trying to implement this feature.
If you faced this issue, go to APIHandler.swift file and comment the validateLoggedIn function's body.

Note: make sure to clean build project to apply this change to framework.
If it solved your problem, let me know to release a fix for this function.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

I don't remember the error to be honest, i already deleted Siwa framework. Because SwiftyInsta itself was enough, but my multiple account problem is still on the table. For now i just won't add multiple account feature.

But now, when i logout and login with other account framework still catches the first account's cookies :/ now i am trying to solve that problem

from swiftyinsta.

RealOlympusDev avatar RealOlympusDev commented on June 11, 2024

I believe I got that error but I also switched back to WebView, I tried the new version of WKWebViewCookie, but I still had to do it twice in order for it to change to the new data

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024

@mkeshnoda this problem is not related to Siwa, I believe this is the problem which prevents you to load your cookies.
@RealOlympusDev I know what you're saying, for sure this is WKWebViewCookie problem, because we delete every cookies before requesting new one.
Just try to comment the function I mentioned above, share the results here. I think it will fix your problem.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

Yup, Now i don't have any problems with Siwa. which, i am not even use it at the moment. My problem is just; when i logout and login with other user i just can't get new user's cookies. I'll try to fix it again and i can i'll share the solution here.

from swiftyinsta.

RealOlympusDev avatar RealOlympusDev commented on June 11, 2024

@mkeshnoda That would be great. Been trying to fix it for a while lol
@TheM4hd1 Which function? WKCookieWebView.preloadWithDomainForCookieSync(urlString: String, completion: (() -> Void)?)?

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024

@mkeshnoda That would be great. Been trying to fix it for a while lol
@TheM4hd1 Which function? WKCookieWebView.preloadWithDomainForCookieSync(urlString: String, completion: (() -> Void)?)?

go to APIHandler.swift file and comment the validateLoggedIn function's body.

from swiftyinsta.

RealOlympusDev avatar RealOlympusDev commented on June 11, 2024

@mkeshnoda That would be great. Been trying to fix it for a while lol
@TheM4hd1 Which function? WKCookieWebView.preloadWithDomainForCookieSync(urlString: String, completion: (() -> Void)?)?

go to APIHandler.swift file and comment the validateLoggedIn function's body.

Oh, ok

from swiftyinsta.

RealOlympusDev avatar RealOlympusDev commented on June 11, 2024

Fixed it! Had to add a completion handler to webViewFinishedToLoadUser and call self.deleteCookies() on completion of webViewFinishedToLoadUser.

from swiftyinsta.

RealOlympusDev avatar RealOlympusDev commented on June 11, 2024

(This requires the developer using the api to call your completion method at the end of their code)

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

Did you add multiple account feature or something else? @RealOlympusDev

from swiftyinsta.

RealOlympusDev avatar RealOlympusDev commented on June 11, 2024

@mkeshnoda I just have a thing that logs in and out, so when you log out and log back in to a different account it doesn’t load the same account anymore.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

Can you share your codebase with me please (only necessary parts) πŸ‘―β€β™‚ Because i did a lot of changes in my InstagramLoginWebView. If you want you can send it to [email protected] as well

from swiftyinsta.

TheM4hd1 avatar TheM4hd1 commented on June 11, 2024

@RealOlympusDev @mkeshnoda

Any fix?

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

From my side, no. unfortunately...

from swiftyinsta.

samma835 avatar samma835 commented on June 11, 2024

Same issue, when I want to login another account, the cookie is still the first one, even if I clean all cookies with the codes inside.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

I still didn't have time to check it out. I'll probably try it again within a week. I'll keep here updated.

from swiftyinsta.

akkayanill avatar akkayanill commented on June 11, 2024

Hi, again @TheM4hd1

I tried @sbertix 's solution. I was able to login but i can't login automatically when i restart my app.
What i did there was;
1- Saved cookies with user defaults.
2- And i passed those cookies into isUSerLoggedIn(instagramCookies : [HTTPCookie]?)
Problem : handler is not working. It returns loginRequired error.

How can i fix this?

from swiftyinsta.

sbertix avatar sbertix commented on June 11, 2024

Prego 😊 @mkeshnoda

from swiftyinsta.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.