Summary. No, that code does not look safe. It doesn't have enough entropy that will be unpredictable to the adversary. I would not re-use that code.
The right way to do it. To generate a random code, I suggest that you read the desired number of bits from
/dev/urandom. This is a one-time code, and it needs to be random and unguessable and cryptographically strong. That's exactly what
/dev/urandom provides. The OS manufacturer has already worked out how to do this securely, after great thought, and that approach has been vetted by security experts. I suggest you simply re-use their existing work.
second_factor_regenerate_token. I don't know if I'm understanding the code properly, but it looks like it doesn't have enough entropy. It hashes the user's username, user's password, HTTP headers, and the current time. That's not enough entropy.
Remember that the purpose of a second factor is to prevent unauthorized individuals who somehow have come to know the user's username and password from gaining access to the system. (If the unauthorized individual doesn't know the user's username and password, then we don't need a second factor; the first factor already blocks them.) So our analysis should start from the assumption that the attacker knows the user's username and password.
Once we make that assumption, the only remaining entropy comes from the current time and the HTTP headers. The time definitely does not have enough entropy: it will be known, or almost known, to the attacker (possibly off by a few seconds, due to imperfect time synchronization, but the attacker can just try all possibilities). I don't know how much entropy will be in the HTTP headers, but it doesn't sound like a solid basis for security.
Therefore, based upon my interpretation of
second_factor_regenerate_token, assuming I am correctly understanding how the code works, I do not think it represents good security engineering. I would not re-use that code.