44
55use Illuminate \Database \Eloquent \Relations \HasOne ;
66use MichaelDzjap \TwoFactorAuth \TwoFactorAuth ;
7+ use Illuminate \Support \Facades \DB ;
78
89trait TwoFactorAuthenticable
910{
@@ -14,7 +15,7 @@ trait TwoFactorAuthenticable
1415 */
1516 public function twoFactorAuth () : HasOne
1617 {
17- return $ this ->hasOne (TwoFactorAuth::class);
18+ return $ this ->hasOne (TwoFactorAuth::class, ' user_id ' , $ this -> getKeyName () );
1819 }
1920
2021 /**
@@ -25,7 +26,15 @@ public function twoFactorAuth() : HasOne
2526 */
2627 public function setTwoFactorAuthId (string $ id ) : void
2728 {
28- $ this ->twoFactorAuth ->update (['id ' => $ id ]);
29+ $ enabled = config ('twofactor-auth.enabled ' , 'user ' );
30+ if ($ enabled === 'user ' ) {
31+ // respect when 2fa is not set for user, never insert
32+ $ this ->twoFactorAuth ->update (['id ' => $ id ]);
33+ }
34+
35+ if ($ enabled === 'enabled ' ) {
36+ $ this ->upsertTwoFactorAuthId ($ id );
37+ }
2938 }
3039
3140 /**
@@ -37,4 +46,23 @@ public function getTwoFactorAuthId() : string
3746 {
3847 return $ this ->twoFactorAuth ->id ;
3948 }
49+
50+ /**
51+ * Create or update a two-factor authentication record with the given id.
52+ *
53+ * @param string $id
54+ * @return void
55+ */
56+ private function upsertTwoFactorAuthId (string $ id ) : void
57+ {
58+ DB ::transaction (function () use ($ id ) {
59+ $ attributes = ['id ' => $ id ];
60+
61+ if (!$ this ->twoFactorAuth ()->exists ()) {
62+ $ this ->twoFactorAuth ()->create ($ attributes );
63+ } else {
64+ $ this ->twoFactorAuth ->update ($ attributes );
65+ }
66+ });
67+ }
4068}
0 commit comments